【问题标题】:Reading n lines from end of text file using python使用python从文本文件末尾读取n行
【发布时间】: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行是否包含空格?
  • 尝试阅读hereherehere给出的答案
  • 文件是python中的迭代器。 for 循环逐行进行,但d.readline() 还会读入另一行,这会导致您跳过行。只需print(l)
  • @DeveshKumarSingh 你的意思是我的文件最后是否有情感线?不,文件在第 74 行终止。
  • @MarkMeyer 谢谢。它解决了我的问题。

标签: python file readlines


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    您可以使用 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 将字符串解释为包含变量名称时包含在 {} 中,从而更容易格式化您的文本。

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2011-08-07
        • 2011-09-21
        • 2023-03-12
        • 2012-07-02
        • 1970-01-01
        • 1970-01-01
        • 2013-03-27
        • 1970-01-01
        • 2021-02-18
        相关资源
        最近更新 更多