for line in file('filename'):

Steve Holden steve at holdenweb.com
Tue Jul 24 10:22:08 EDT 2007


Yoav Goldberg wrote:
> 
> I use the idiom "for line in file('filename'): do_something(line)" quite 
> a lot.
> 
> Does it close the opened file at the end of the loop, or do I have to 
> explicitly save the file object and close it afterward?
> 
The file will *normally* be closed in most Python implementations, but 
it's good practice to close it explicitly. Google for "defensive 
programming" to find out why.

In 2.5 you can use the "with" statement to get an explicit close without 
having to write it. The following code comes from "What's new in Python 
2.5":

from __future__ import with_statement
with open('/etc/passwd', 'r') as f:
     for line in f:
         print line
         ... more processing code ...

This is because the open() built-in now returns a "context manager" 
object that closes the file automatically.

regards
  Steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd           http://www.holdenweb.com
Skype: holdenweb      http://del.icio.us/steve.holden
--------------- Asciimercial ------------------
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
----------- Thank You for Reading -------------




More information about the Python-list mailing list