Ignore last \n when using readlines with python

本秂侑毒 提交于 2020-01-03 10:58:31

问题


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


回答1:


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]



回答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.



来源:https://stackoverflow.com/questions/4006441/ignore-last-n-when-using-readlines-with-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!