Search code examples
pythonfile-iocontextmanager

Does opening a file and performing an operation on that file in one line close the file?


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?


Solution

  • 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.