Python中是否有一个文件管理库具有功能:一旦某个行已在文件中被读取,它会删除它(该行) )?
我需要它知道,万一程序因错误而停止,它在文件中的位置结束了。我现在所做的是重写整个文件,除了它正在读取的行之外
根据您的要求(了解发生错误时进程在文件中的哪个位置停止),您可以考虑一种替代方法,该方法比每次重写文件所需的开销更少:
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))