Append a text line to a file and remove the first one if there are more than 4 lines in python

不想你离开。 提交于 2019-12-11 15:34:34

问题


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:

  1. 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)
  2. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!