How should I read a file line-by-line in Python?

Viewed 360177

In pre-historic times (Python 1.4) we did:

fp = open('filename.txt')
while 1:
    line = fp.readline()
    if not line:
        break
    print(line)

after Python 2.1, we did:

for line in open('filename.txt').xreadlines():
    print(line)

before we got the convenient iterator protocol in Python 2.3, and could do:

for line in open('filename.txt'):
    print(line)

I've seen some examples using the more verbose:

with open('filename.txt') as fp:
    for line in fp:
        print(line)

is this the preferred method going forwards?

[edit] I get that the with statement ensures closing of the file... but why isn't that included in the iterator protocol for file objects?

3 Answers
Related