Does opening a file and performing an operation on that file in one line close the file?
Question:
Is opening a file and subsequently performing an operation on that file in the same line safe to do without closing the file afterwards?
For example, if I were using the zipfile
module and wanted to obtain a list of files inside of a zip called file_list
, would it be safe to do the following:
import zipfile
import os
zip_path = os.path(...)
file_list = zipfile.ZipFile(zip_path).namelist()
Of course, I know this code would accomplish the same thing safely, albeit in 2 lines:
import zipfile
import os
zip_path = os.path(...)
with zipfile.ZipFile(zip_path) as my_zip:
file_list = my_zip.namelist()
Which is better?
Answers:
From the docs:
ZipFile.close()
Close the archive file. You must call close()
before exiting your program or essential records will not be written.
Generally speaking, it’s almost always better to use a context manager. It is considered neater and safer.
It will close the file when it’s garbage collected
# ZipFile in zipfile.py
def __del__(self):
"""Call the "close()" method in case the user forgot."""
self.close()
If you use that one liner it doesn’t create a ref so it should get disposed and in turn closed. But you’re relying on an implementation detail of when the GC runs which isn’t the best idea, you’re better off using with
.
For instance the one liner wouldn’t behave the same way with pypy
Is opening a file and subsequently performing an operation on that file in the same line safe to do without closing the file afterwards?
For example, if I were using the zipfile
module and wanted to obtain a list of files inside of a zip called file_list
, would it be safe to do the following:
import zipfile
import os
zip_path = os.path(...)
file_list = zipfile.ZipFile(zip_path).namelist()
Of course, I know this code would accomplish the same thing safely, albeit in 2 lines:
import zipfile
import os
zip_path = os.path(...)
with zipfile.ZipFile(zip_path) as my_zip:
file_list = my_zip.namelist()
Which is better?
From the docs:
ZipFile.close()
Close the archive file. You must call
close()
before exiting your program or essential records will not be written.
Generally speaking, it’s almost always better to use a context manager. It is considered neater and safer.
It will close the file when it’s garbage collected
# ZipFile in zipfile.py
def __del__(self):
"""Call the "close()" method in case the user forgot."""
self.close()
If you use that one liner it doesn’t create a ref so it should get disposed and in turn closed. But you’re relying on an implementation detail of when the GC runs which isn’t the best idea, you’re better off using with
.
For instance the one liner wouldn’t behave the same way with pypy