在Python中读取文本文件时输出不正确

2024-04-18 00:43:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要读文件的前30行。你知道吗

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

300

我错过什么了吗?你知道吗


Tags: 文件lenaswithopenfilenamelinesprint
2条回答

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

看完这些评论后,我决定回答这个问题:如何阅读文件的前30行。答案是:readline()

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

完成。你知道吗

相关问题 更多 >

    热门问题