【问题标题】:Incorrect output while reading text file in Python在 Python 中读取文本文件时输出不正确
【发布时间】:2015-10-08 09:52:40
【问题描述】:

我需要读取文件的前 30 行。

with open(filename) as f:
    lines = f.readlines(30)
print len(lines)

300

我错过了什么吗?

【问题讨论】:

标签: python file io readlines


【解决方案1】:

阅读完 cmets 后,我决定对这个问题给出“答案”:如何从文件中读取前 30 行。答案是:readline()

lines = []
for i in range(30):
    lines.append(f.readline())

完成。

【讨论】:

    【解决方案2】:

    根据https://docs.python.org/2/library/stdtypes.html#file.readlines30 不是要读取的行数。它是以 bytes 给出的缓冲区提示。

    【讨论】:

    • 这不是一个答案,它是有效的评论,但它不能解决问题。
    • 怎么样?它解释了为什么代码没有给出预期的输出。
    • 我猜其他关于该主题的答案是错误的。
    猜你喜欢
    • 2021-09-01
    • 2015-05-24
    • 1970-01-01
    • 2015-07-02
    • 2013-03-08
    • 2019-06-16
    • 2019-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多