在 python 中使用 readlines 时忽略最后一个 \n
我有一个从中读取的文件,如下所示:
1 value1
2 value2
3 value3
该文件的最后一行可能有也可能没有尾随 \n。
我正在使用的代码工作得很好,但如果有尾随 \n 它就会失败。
抓住这个的最好方法是什么?
我的参考代码:
r=open(sys.argv[1], 'r');
for line in r.readlines():
ref=line.split();
print ref[0], ref[1]
这会失败:
回溯(最近一次调用最后一次):
文件“./test”,第 14 行,位于
打印 ref[0], ref[1]
IndexError:列表索引超出范围
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以忽略仅包含空格的行:
You can ignore lines that contain only whitespace:
我认为你没有告诉我们整个故事。
line.split()
将给出相同的结果,无论最后一行是否由\n
终止。请注意,最后一行在文件中以
\n
终止是常见的行为,人们偶尔会被未如此终止的行所困扰。如果你要做类似的事情:
你将
能够自己准确地检测到正在发生的事情,而不是让我们猜测。
如果正如 @Mark Byers 推测的那样,您的最后一行是空的或仅由空格组成,您可以通过以下更简单的代码忽略该行(以及所有其他此类行):
另请考虑您只有一个的可能性最后一行中的字段,而不是 0 或 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:
instead of
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:
Please also consider the possibility that you have only one field, not 0 or 2, in your last line.