Nathan
Nathan

Reputation: 4347

Pythonic way to read file line by line?

What's the Pythonic way to go about reading files line by line of the two methods below?

with open('file', 'r') as f:
    for line in f:
        print line

or

with open('file', 'r') as f:
    for line in f.readlines():
        print line

Or is there something I'm missing?

Upvotes: 7

Views: 9632

Answers (3)

g.d.d.c
g.d.d.c

Reputation: 48028

File handles are their own iterators (specifically, they implement the iterator protocol) so

with open('file', 'r') as f:
  for line in f:
    # code

Is the preferred usage. f.readlines() returns a list of lines, which means absorbing the entire file into memory -> generally ill advised, especially for large files.

It should be pointed out that I agree with the sentiment that context managers are worthwhile, and have included one in my code example.

Upvotes: 12

DaveP
DaveP

Reputation: 7102

Of the two you presented, the first is recommended practice. As pointed out in the comments, any solution (like that below) which doesn't use a context manager means that the file is left open, which is a bad idea.

Original answer which leaves dangling file handles so shouldn't be followed However, if you don't need f for any purpose other than reading the lines, you can just do:

for line in open('file', 'r'):
    print line

Upvotes: 7

Yunzhi Ma
Yunzhi Ma

Reputation: 672

theres' no need for .readlines() method call.

PLUS: About with statement

The execution behavior of with statement is as commented below,

with open("xxx.txt",'r') as f:    
                                  // now, f is an opened file in context
    for line in f:
        // code with line

pass                              // when control exits *with*, f is closed
print f                           // if you print, you'll get <closed file 'xxx.txt'>

Upvotes: 1

Related Questions