0

This code works but I want to close opened files. How to change this code ?

with open(output_file, "w", newline='') as f_output:
    try:
        os.remove(output_file)                                                          # Delete old file
    except OSError:
        pass
    for r in range(len(new_list)):
        open(output_file, "a").writelines(str(second_list[r] + '\n'))
Mazdak
  • 105,000
  • 18
  • 159
  • 188
Luk
  • 185
  • 1
  • 2
  • 10
  • Why you are trying to remove the `output_file` and then you are opening the file in append mode? – Mazdak May 18 '16 at 15:15
  • If old file exists - delete it, write new file and append new line in file. Else, write file and append new file in file. – Luk May 18 '16 at 15:34
  • Why you don't use `with` statement again? Also you better to move your `for` loop out of `with`. – Mazdak May 18 '16 at 15:53
  • Can you show me a example how should this looks ? – Luk May 19 '16 at 07:00

1 Answers1

0

The file closes automatically.

If you want to close the file then please change it to (I left it as output_file because it looks like a variable) f_output = open(output_file, "w")

then you can just say f_output.close() when you want to close the file.

Hezekiah Bodine
  • 141
  • 1
  • 13