Skip to main content
 首页 » 编程设计

python之写入文件,以便保留最后 N 行

2024年10月01日8Renyi-Fan

我试图保留一个只有 10 个条目的文件。

每次我写一个新的,最旧的条目被最新的取代;所以总行数总是 10。

文件示例:

abcde-12345 
akmjk-13249 
ofdsi-01230 
faaoj-10293 
famdk-05931 
foajq-10592 
xmdsj-19234 
boxqa-12130 
fdlsp-95392 
paidf-19341 

当我使用 append 命令在此文件上添加新行时,它会增加文件的总行数,因此每次添加行时文件都会增长。目标是在底部追加行,删除文件的第一行,所以最旧的条目被删除,新的添加在底部,文件中的总行数始终等于 10。

我的方法是

-read the file 
-save the last 9 lines in a new file 
-add the 10th line, which is the new one 
-delete the old file, and save the new file with the same name. 

这有麻烦、慢、效率低的问题。在 Shell 脚本中我可以很容易地做到这一点,但由于我使用 python,我希望有一种更简单的方法来做到这一点

请您参考如下方法:

使用 deque 作为缓冲区,使用 maxlen=10,追加到 deque,然后从 deque 写入:

Juans-MBP:workspace juan$ cat 10lines.txt 
first line 
second line 
third line 
fourth line 
fith line 
sixth line 
seventh line 
eigth line 
ninth line 
tenth line 
Juans-MBP:workspace juan$ python 
Python 3.5.2 |Anaconda custom (x86_64)| (default, Jul  2 2016, 17:52:12) 
[GCC 4.2.1 Compatible Apple LLVM 4.2 (clang-425.0.28)] on darwin 
Type "help", "copyright", "credits" or "license" for more information. 
>>> from collections import deque 
>>> with open('10lines.txt') as f: 
...     buffer = deque(f, maxlen=10) 
... 
>>> buffer.append('first new line\n') 
>>> buffer.append('second new line\n') 
>>> with open('10lines.txt', 'w') as f: 
...     f.writelines(buffer) 
... 
>>> exit() 
Juans-MBP:workspace juan$ cat 10lines.txt 
third line 
fourth line 
fith line 
sixth line 
seventh line 
eigth line 
ninth line 
tenth line 
first new line 
second new line 
Juans-MBP:workspace juan$ 

请注意,您必须注意确保追加的行有换行符,因为正如名称所暗示的那样,f.writelines 没有添加换行符。