Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is file automatically closed if read in same line as opening?

Tags:

python

file

io

If I do (in Python):

text = open("filename").read()

is the file automatically closed?

like image 709
abalter Avatar asked Dec 19 '22 13:12

abalter


1 Answers

The garbage collector would be activated at some point, but you cannot be certain of when unless you force it.

The best way to ensure that the file is closed when you go out of scope just do this:

with open("filename") as f: text = f.read()

also one-liner but safer.

like image 180
Jean-François Fabre Avatar answered Dec 26 '22 00:12

Jean-François Fabre