繁体   English   中英

使用python从文本文件末尾读取n行

[英]Reading n lines from end of text file using python

我正在尝试编写一个程序来读取和打印 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())添加到函数时为什么不打印某些索引和行的原因。 以及为什么打印的索引和行不匹配。

您可以立即使用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)

您可以使用 Python 的readlines()函数将文件作为行列表读取。 然后,您可以使用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')

您还可以添加f作为字符串的前缀,Python 然后将字符串解释为包含变量名称时包含{}使得更容易格式化您的文本。

读取文件两次似乎有点低效,但既然你已经这样做了,你可以通过以下方式使用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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM