简体   繁体   English

使用python的readlines时忽略last \\ n

[英]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. 该文件在最后一行中可能有也可能没有尾随\\ n。

The code I'm using works great, but if there is an trailing \\n it fails. 我正在使用的代码效果很好,但如果有一个尾随\\ n它失败了。
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): Traceback(最近一次调用最后一次):
File "./test", line 14, in 文件“./test”,第14行,in
print ref[0], ref[1] print ref [0],ref [1]
IndexError: list index out of range IndexError:列表索引超出范围

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. 无论最后一行是否以\\n终止, line.split()都会给出相同的结果。

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. 请注意, \\n终止的文件中的最后一行是USUAL行为,并且人们偶尔会被未被终止的行打扰。

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: 如果@Mark Byers推测,你的最后一行是空的或只包含空格,你可以通过这个更简单的代码忽略该行(和所有其他这样的行):

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. 还请考虑在最后一行中只有一个字段,而不是0或2的可能性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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