删除文件中已读取行的函数

问题描述 投票:0回答:1

Python中是否有一个文件管理库具有功能:一旦某个已在文件中被读取,它会删除行) )?

我需要它知道,万一程序因错误而停止,它在文件中的位置结束了。我现在所做的是重写整个文件,除了它正在读取的行之外

python function file
1个回答
0
投票
在Python中,没有内置的文件管理库直接支持从文件中读取一行然后删除它。 正如您所做的那样,标准方法涉及读取文件、处理行,然后写回未处理的行,这主要是由于文件 I/O 在大多数操作系统中的工作方式所致。

根据您的要求(了解发生错误时进程在文件中的哪个位置停止),您可以考虑一种替代方法,该方法比每次重写文件所需的开销更少:

  1. 使用单独的文件或变量跟踪进度:您可以跟踪已处理的行号,而不是从原始文件中删除行。如果发生错误,您可以将此行号保存到单独的文件或持久存储机制中。重新启动后,您将阅读此进度指示器并跳至您之前停止的行。

  2. 处理和存档已处理的行:不要从原始文件中删除行,而是将已处理的行移动到单独的“存档”文件中。这种方法保持原始文件完整并提供已处理内容的清晰记录。

这是代码。

def process_file(filepath, progress_filepath): try: with open(progress_filepath, 'r') as progress_file: last_processed_line_number = int(progress_file.read()) except FileNotFoundError: last_processed_line_number = 0 with open(filepath, 'r') as file: lines = file.readlines() for i, line in enumerate(lines, 1): if i <= last_processed_line_number: continue # Skip already processed lines # Process the line here print(f"Processing line {i}: {line}", end='') # Update the progress file with open(progress_filepath, 'w') as progress_file: progress_file.write(str(i))
    
© www.soinside.com 2019 - 2024. All rights reserved.