views:

56

answers:

2

Hi,

I have a file I read from that looks like:

1   value1
2   value2
3   value3

The file may or may not have a trailing \n in the last line.

The code I'm using works great, but if there is an trailing \n it fails.
Whats the best way to catch this?

My code for reference:

r=open(sys.argv[1], 'r');
for line in r.readlines():
    ref=line.split();
    print ref[0], ref[1]

Which would fail with a:
Traceback (most recent call last):
File "./test", line 14, in
print ref[0], ref[1]
IndexError: list index out of range

+2  A: 

You can ignore lines that contain only whitespace:

for line in r.readlines():
    line = line.rstrip()      # Remove trailing whitespace.
    if line:                  # Only process non-empty lines.
        ref = line.split();
        print ref[0], ref[1]
Mark Byers
rstrip is redundant; split ignores leading/training whitespace
John Machin
+1  A: 

I don't think that you have told us the whole story. line.split() will give the same result irrespective of whether the last line is terminated by \n or not.

Note that the last line in a file being terminated by \n is the USUAL behaviour, and people are occasionally bothered by a line that's not so terminated.

If you were to do something like:

print repr(line), repr(ref)

instead of

print ref[0], ref[1]

you would be able to detect for yourself exactly what is going on, instead of leaving us to guess.

If as @Mark Byers surmises, your last line is empty or consists only of whitespace, you can ignore that line (and all other such lines) by this somewhat more simple code:

for line in r: # readlines is passe
    ref = line.split() # split() ignores trailing whitespace
    if ref:
        print ref[0], ref[1]

Please also consider the possibility that you have only one field, not 0 or 2, in your last line.

John Machin
I think he meant that there is yet another line, consisting only of `\n`, at the end... (file ending with "...value3\n\n")
Steven