Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is file closing necessary in this situation?

Tags:

python

file

if I have:

fdata = open(pathf, "r").read().splitlines()

Will the file automatically close after getting the data? If not how can I close it since fdata is not a handle?

Thank you

like image 962
SJPRO Avatar asked Dec 03 '22 11:12

SJPRO


2 Answers

Use

with open(pathf, "r") as r:
    fdata = r.read().splitlines()
# as soon as you leave the with-scope, the file is autoclosed, even if exceptions happen.

Its not only about auto-closing, but also about correct closing in case of exceptions.

Doku: methods of file objects

It is good practice to use the with keyword when dealing with file objects. The advantage is that the file is properly closed after its suite finishes, even if an exception is raised at some point. Using with is also much shorter than writing equivalent try-finally blocks:

If you’re not using the with keyword, then you should call f.close() to close the file and immediately free up any system resources used by it.
If you don’t explicitly close a file, Python’s garbage collector will eventually destroy the object and close the open file for you, but the file may stay open for a while. Another risk is that different Python implementations will do this clean-up at different times.

like image 198
Patrick Artner Avatar answered Dec 24 '22 13:12

Patrick Artner


The file will be automatically closed during exit or garbage collection. But as best practices matter, the better approach would be to use a context manager such as below:

with open(pathf, "r") as f:
    fdata = f.read().splitlines()

Thank you.

like image 43
T.S. Avatar answered Dec 24 '22 14:12

T.S.