简体   繁体   中英

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

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]

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM