Is it necessary to close files after writing JSON data to them in Python

10,307

Solution 1

The advantage of using the 'with' construct is precisely that you won't have to worry about closing the file here, as it will automatically be closed when the file goes out of scope.

Solution 2

In cpython, files close when their refcount goes to zero, even if you don't use a with statement. Depending on how you use the file object, you run the risk that circular references keep this from happening. But there are conditions like some signals where regular cleanup doesn't happen. In that case, you may loose whatever data is still in the local process file buffer that hasn't been flushed.

The least risky solution is to use with statements when possible and try/finally blocks that clean up files otherwise.

Share:
10,307
Mustard Tiger
Author by

Mustard Tiger

Updated on June 28, 2022

Comments

  • Mustard Tiger
    Mustard Tiger almost 2 years

    If i use:

    with open(Name, 'w') as outfile:
        json.dump(json_object, outfile)
    

    is it necessary to use the file.close() method afterwards?

    In general cases like writing normal strings to files in python what is the consequence of not using the file.close() method?