我正在尝试编写一个程序来读取和打印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())
添加到函数中时为什么某些索引和行没有打印的原因。以及为什么打印的索引和行不匹配。
答案 0 :(得分:0)
您可以使用readlines()
和print(v)
立即进行操作:
n = 5
with open(x, 'r') as fp:
lines = fp.readlines()
total_length = len(lines)
threshold = total_length - n
for i, v in enumerate(lines):
if i >= threshold:
print(i, v)
答案 1 :(得分:0)
您可以使用Python的readlines()
函数以行列表的形式读取文件。然后,您可以使用draft-js-export-html
来确定返回的列表中有多少行:
len()
您还可以在字符串的前面添加n = 5
def readfile(x):
with open(x) as f_input:
lines = f_input.readlines()
total_lines = len(lines)
print(f"The total number of lines in the file is {total_lines}.")
print(f"The last {n} lines of the file are:")
for line_number in range(total_lines-n, total_lines):
print(f"{line_number+1}\n{lines[line_number]}", end='')
readfile('input.txt')
作为前缀,Python会在用f
括起来时将字符串解释为包含变量名,从而使文本格式设置更加容易。
答案 2 :(得分:0)
两次读取文件似乎效率不高,但是既然您已经这样做了,则可以通过以下方式使用collections.deque
来轻松地完成所需的操作:
from collections import deque
def print_last_lines(filename, linecount, n):
# Get the last n lines of the file.
with open(filename) as file:
last_n_lines = deque(file, n)
print("The total number of lines in the file is", linecount)
print("The last", n, "lines of the file are:")
for i, line in enumerate(last_n_lines, 1):
print(linecount-n+i)
print(line, end='')
filename = 'lastlines.txt'
n = 5
# Count lines in file.
with open(filename) as file:
linecount = len(list(file))
print_last_lines(filename, linecount, n)