使用python的readlines时忽略last \n

fak*_*ker 6 python readlines

我有一个我从中读取的文件,如下所示:

1   value1
2   value2
3   value3
Run Code Online (Sandbox Code Playgroud)

该文件在最后一行中可能有也可能没有尾随\n.

我正在使用的代码效果很好,但如果有一个尾随\n它失败了.
什么是抓住这个的最好方法?

我的代码供参考:

r=open(sys.argv[1], 'r');
for line in r.readlines():
    ref=line.split();
    print ref[0], ref[1]
Run Code Online (Sandbox Code Playgroud)

哪一个会失败的:
Traceback(最近一次调用最后一次):
文件"./test",第14行,在
print ref [0]中,ref [1]
IndexError:列表索引超出范围

Mar*_*ers 8

您可以忽略仅包含空格的行:

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]
Run Code Online (Sandbox Code Playgroud)