【发布时间】:2019-06-30 15:41:42
【问题描述】:
我正在尝试编写一个程序来读取和打印 python 中文本文件的最后 n 行。 我的文本文件有 74 行。 我写了一个类似下面的函数来读取最后 n 行。
s=74 //Got this using another function, after enumerating the text file
n=5//
def readfile(x):
print("The total number of lines in the file is",s)
startline=(s-n)
print("The last",n,"lines of the file are")
with open(x,'r') as d:
for i, l in enumerate(d):
if (i>=startline):
print(i)
print(d.readline())`
我想要的输出是:
The total number of lines in the file is 74
The last 5 lines of the file are
69
Resources resembled forfeited no to zealously.
70
Has procured daughter how friendly followed repeated who surprise.
71
Great asked oh under on voice downs.
72
Law together prospect kindness securing six.
73
Learning why get hastened smallest cheerful.
但是在运行时,我的输出看起来像
The total number of lines in the file is 74
69
Has procured daughter how friendly followed repeated who surprise.
70
Law together prospect kindness securing six.
71
枚举的索引与行不匹配,并不是所有的都被打印出来。 循环也打印索引 72 和 73 的空格。
如果我在函数中注释掉以下行:
`#print(d.readline())`
然后我的输出变成:
The total number of lines in the file is 74
The last 5 lines of the file are
69
70
71
72
73
空格消失了,所有索引都被打印出来了。
当print(d.readline()) 添加到函数中时,我无法找出为什么不打印某些索引和行。以及为什么打印的索引和行不匹配。
【问题讨论】:
-
Reading n lines from end of text file using python,那n行是否包含空格? -
文件是python中的迭代器。 for 循环逐行进行,但
d.readline()还会读入另一行,这会导致您跳过行。只需print(l)。 -
@DeveshKumarSingh 你的意思是我的文件最后是否有情感线?不,文件在第 74 行终止。
-
@MarkMeyer 谢谢。它解决了我的问题。