Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for line in open(filename)

I frequently see python code similar to

for line in open(filename):     do_something(line) 

When does filename get closed with this code?

Would it be better to write

with open(filename) as f:     for line in f.readlines():         do_something(line) 
like image 478
foosion Avatar asked Sep 25 '09 17:09

foosion


2 Answers

filename would be closed when it falls out of scope. That normally would be the end of the method.

Yes, it's better to use with.

Once you have a file object, you perform all file I/O by calling methods of this object. [...] When you are done with the file, you should finish by calling the close method on the object, to close the connection to the file:

input.close() 

In short scripts, people often omit this step, as Python automatically closes the file when a file object is reclaimed during garbage collection (which in mainstream Python means the file is closed just about at once, although other important Python implementations, such as Jython and IronPython, have other, more relaxed garbage collection strategies). Nevertheless, it is good programming practice to close your files as soon as possible, and it is especially a good idea in larger programs, which otherwise may be at more risk of having excessive numbers of uselessly open files lying about. Note that try/finally is particularly well suited to ensuing that a file gets closed, even when a function terminates due to an uncaught exception.

Python Cookbook, Page 59.

like image 132
Esteban Küber Avatar answered Sep 21 '22 09:09

Esteban Küber


Drop .readlines(). It is redundant and undesirable for large files (due to memory consumption). The variant with 'with' block always closes file.

with open(filename) as file_:     for line in file_:         do_something(line) 

When file will be closed in the bare 'for'-loop variant depends on Python implementation.

like image 43
jfs Avatar answered Sep 20 '22 09:09

jfs