0

If I want to write data to a file using json library, Is it ok if I do this?:

...
json.dump(my_data, open('my_file_path', 'w+'))
...

Or do I have to do this?:

...
with open('my_file_path', 'w+') as my_file:
    json.dump(my_data, my_file)
...

Does the first option also closes the file immediatly?

Alejo Dev
  • 2,290
  • 4
  • 29
  • 45
  • 2
    The `with` context manager also *closes* the file when the context ends, so it's probably better. – jonrsharpe Sep 17 '20 at 14:44
  • I know that, but because I am not creating any reference to the file, maybe I get the same result with the inline option – Alejo Dev Sep 17 '20 at 14:46
  • 1
    As I understand it the file is closed when the handle is garbage collected, but you don't have the same control over when that happens. – jonrsharpe Sep 17 '20 at 16:29
  • 1
    I had a similar question and people pointed me to another question with answers, so I flag this one as duplicate too for others to find good answers. go here -> [Is explicitly closing files important?](https://stackoverflow.com/questions/7395542/is-explicitly-closing-files-important) – Romain Vincent Nov 02 '20 at 13:55

0 Answers0