Ignore last \n when using readlines with python

faker picture faker · Oct 24, 2010 · Viewed 16.8k times · Source

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

Answer

Mark Byers picture Mark Byers · Oct 24, 2010

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]