问题
I have an IRC client that people are chatting on while I broadcast my desktop. I wanted to show this on my broadcast and found a handy shock-wave flash title plug-in that can read text files and display them on the screen.
My IRC client uses python scripts and can call a function every time someone write a message.
I can write these text lines to a text file as they come in but I want some way of coding in python when there are more than 'say 4' lines of text in the file it removes the top one when adding the next one.
I planned to do so by reading the text file when the append line function is called, reading the last 3 lines adding the new one then re-writing it to the original file.
Of course when the script first runs there should be less then 3 lines in the file so the python should account for that also and only read the last 2 or 1 or 0 depending...
I tried writing some code in a previous question but it didn't work so I won't include it here.
回答1:
You shouldn't give up too easily, the accepted answer to your previous question nearly did it.
You only need to do the following:
- Open the input file, using a
deque
to obtain the last few lines, and append your new line
(don't forget to use a new line separator\n
) - Re-open the file as an output file and write your collection of lines.
from collections import deque
path = 'test.txt'
with open(path, 'r') as file:
lines = deque(file, 4)
lines.append("\nthis is an additional line.")
with open(path, 'w') as file:
file.writelines(lines)
来源:https://stackoverflow.com/questions/15648578/append-a-text-line-to-a-file-and-remove-the-first-one-if-there-are-more-than-4-l