Pythonic way of reading a textfile line by line without throwing an exception

Matimus mccredie at
Wed Aug 29 02:25:15 CEST 2007

> fp=open(filename, 'r')
> for line in fp:
>     # do something with line
> fp.close()

Or, if you are using Python 2.5+, you can use the file context via the
`with' statement.

from __future__ import with_statement # this line won't be needed in
Python 2.6+

with open(filename, 'r') as fp:
    for line in fp:
        # do something with line

This basicly just closes the file automatically (even if there is an
exception) when the context (part indented under `with') is exited.
This is a new feature, but probably the most pythonic way of doing it.
That will be especially true in the future.


More information about the Python-list mailing list