Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do files automatically close if I don't assign them to a variable? [duplicate]

Possible Duplicate:
Is close() necessary when using iterator on a Python file object

for line in open("processes.txt").readlines():
    doSomethingWith(line)

Take that code for example. There's nothing to call close() on. So does it close itself automatically?

like image 870
temporary_user_name Avatar asked Dec 15 '22 16:12

temporary_user_name


1 Answers

Files will close when the corresponding object is deallocated. The sample you give depends on that; there is no reference to the object, so the object will be removed and the file will be closed.

Important to note is that there isn't a guarantee made as to when the object will be removed. With CPython, you have reference counting as the basis of memory management, so you would expect the file to close immediately. In, say, Jython, the garbage collector is not guaranteed to run at any particular time (or even at all), so you shouldn't count on the file being closed and should instead close the file manually or (better) use a with statement.

like image 80
Michael J. Barber Avatar answered May 04 '23 01:05

Michael J. Barber