-2

Just trying to do a very standard open and iterate through a file:

file = open('test2.txt', 'r')
for line in file:
    #first,sec = line.split(',')
    #print "first", first
    print line

However, it only prints the last line.

Changing to file.readline() solves this problem. Why not the first way?

user2963623
  • 2,207
  • 1
  • 12
  • 25
user0
  • 2,237
  • 6
  • 21
  • 59
  • 2
    You should not reuse the name `file`, but otherwise there's no error demonstrated here. Do you at any point call something like `fh.readlines()`, next(fh), `list(fh)` or something similar? The code here isn't indented properly, so mustn't be your actual code. Also, can you vouch for valid line endings in your input data? – g.d.d.c Aug 16 '14 at 04:42
  • Strange, works fine as expected on my computer. Is this the exact code? – user2963623 Aug 16 '14 at 04:54
  • That sounds like a line ending problem. – Ry- Aug 16 '14 at 05:05

2 Answers2

2

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)
Andy
  • 43,170
  • 54
  • 150
  • 214
  • Although my problem was caused by something that couldn't be deduced by the question, this was a very good answer – user0 Aug 16 '14 at 05:05
1

The first way, that will be unefficient if it comes to bigger files:

file = open('test2.txt', 'r')
for line in file.readlines():
    print line

Another way (mentioned in How to read large file, line by line in python):

with open('a.txt','r') as f:
  for line in f:
    print line
Community
  • 1
  • 1
Serjik
  • 9,013
  • 6
  • 57
  • 65
  • 5
    While not incorrect, this is unnecessary, and loads the entire file into memory. That might not matter, but it might be critical. – g.d.d.c Aug 16 '14 at 04:43