Don't use readlines
, as has been suggested in other answers. It is slow
Instead, do this:
with open('test2.txt') as f:
for line in f:
print line
The advantage here is that you are not reading the entire file into memory first and then processing. Additionally, by using the with
, your fill will be automatically closed when you leave that block.
If you need to make your file into a list (as readlines
does), then make that explicit.
with open('foo.txt') as f:
lines = list(f)
Now lines
is a list that you can iterate over multiple times.
for line in lines:
print line
for line in lines:
print "Loop 2 - %s" % (line)