在 python 中使用 readlines 时忽略最后一个 \n

发布于 2024-09-29 12:17:59 字数 425 浏览 7 评论 0原文

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

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

烟酉 2024-10-06 12:17:59

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

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]

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]
两相知 2024-10-06 12:17:59

我认为你没有告诉我们整个故事。 line.split() 将给出相同的结果,无论最后一行是否由 \n 终止。

请注意,最后一行在文件中以 \n 终止是常见的行为,人们偶尔会被未如此终止的行所困扰。

如果你要做类似的事情:

print repr(line), repr(ref)

你将

print ref[0], ref[1]

能够自己准确地检测到正在发生的事情,而不是让我们猜测。

如果正如 @Mark Byers 推测的那样,您的最后一行是空的或仅由空格组成,您可以通过以下更简单的代码忽略该行(以及所有其他此类行):

for line in r: # readlines is passe
    ref = line.split() # split() ignores trailing whitespace
    if ref:
        print ref[0], ref[1]

另请考虑您只有一个的可能性最后一行中的字段,而不是 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:

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文