Ignore last \n when using readlines with python
Asked Answered
K

2

6

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

Korfonta answered 23/10, 2010 at 22:44 Comment(0)
I
8

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]
Inferior answered 23/10, 2010 at 22:49 Comment(1)
rstrip is redundant; split ignores leading/training whitespaceRiva
R
2

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.

Riva answered 23/10, 2010 at 23:7 Comment(1)
I think he meant that there is yet another line, consisting only of \n, at the end... (file ending with "...value3\n\n")Rabb

© 2022 - 2024 — McMap. All rights reserved.