Skip to main content
 首页 » 编程设计

python之如何在 Python 中读取 txt 文件的特定部分

2025年05月04日20cloudgamer

我需要从一个 txt 文件中提取一部分文本。
该文件如下所示:

开始工作 DD/MM/YYYY HH: MM: SS
... 文本行 ...
... 更多文本行 ...
开始工作 DD/MM/YYYY HH: MM: SS
... 我想要的文本行 ...
...我想要的更多文本行...

  • 文件以 STARTINGWORK 开头,以文本行结尾。
    我需要在没有 STARTINGWORK str 的情况下提取最后一个 STARTINGWORK 之后的最终文本部分

我尝试使用 3 个 for 循环(一个开始,另一个读取中间行,最后一个结束)

     file = "records.txt" 
     if file.endswith (".txt"): 
       if os.path.exists (file): 
         lines = [line.rstrip ('\ n') for line in open (file)] 
         for line in lines: 
             #extract the portion 

请您参考如下方法:

您可以使用file_read_backwards 模块从头到尾读取文件。如果文件很大,它可以帮助您节省时间:

from file_read_backwards import FileReadBackwards 
 
with FileReadBackwards("records.txt") as file: 
    portion = list() 
    for line in file: 
         if not line.startswith('STARTINGWORKING'): 
            portion.append(line) 
         else: 
            break 
portion.reverse() 

部分 包含所需的行。