Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore last \n when using readlines with python

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

like image 856
faker Avatar asked Oct 23 '10 22:10

faker


1 Answers

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]
like image 180
Mark Byers Avatar answered Sep 22 '22 01:09

Mark Byers