【发布时间】:2025-11-27 23:35:01
【问题描述】:
here 和 here 已经提出过这个问题,但没有一个解决方案适合我。
如何在 Python 3 中有效地从大文件中删除 first 行?
我正在编写一个需要记录的程序,并且日志文件具有可配置的最大大小,可以是无限的。因此,我不想使用readlines() 或类似的方法,因为这些方法会占用大量内存。速度不是一个大问题,但如果它可以在重写整个文件并且没有临时文件的情况下完成,那就太好了。
解决方案需要跨平台。
示例日志文件:
[09:14:56 07/04/17] [INFO] foo
[23:45:01 07/04/17] [WARN] bar
[13:45:28 08/04/17] [INFO] foobar
... many thousands more lines
输出:
[23:45:01 07/04/17] [WARN] bar
[13:45:28 08/04/17] [INFO] foobar
... many thousands more lines
这段代码将循环运行:
while os.path.getsize(LOGFILE) > MAXLOGSIZE:
# remove first line of file
以下解决方案均无效且内存效率高:
解决方案 #1 - 有效但效率低
with open('file.txt', 'r') as fin:
data = fin.read().splitlines(True)
with open('file.txt', 'w') as fout:
fout.writelines(data[1:])
解决方案 #2 - 不起作用,文件为空
import shutil
source_file = open('file.txt', 'r')
source_file.readline()
target_file = open('file.txt', 'w')
shutil.copyfileobj(source_file, target_file)
解决方案 #3 - 有效,但使用额外的文件:
with open("file.txt",'r') as f:
with open("new_file.txt",'w') as f1:
f.next() # skip header line
for line in f:
f1.write(line)
【问题讨论】:
标签: python python-3.x logging file-io