How to delete the first line of a text file?

前端 未结 8 2015
醉梦人生
醉梦人生 2020-11-29 09:10

I have been searching online, but have not found any good solution.

Here is my text file:

[54, 95, 45, -97, -51, 84, 0, 32, -55, 14, 50, 54, 68, -3,          


        
8条回答
  •  抹茶落季
    2020-11-29 09:52

    Safer to use one open for read & write, if you want to use the file from another thread/process:

    def pop(self, file):
        with open(file, 'r+') as f: # open file in read / write mode
            firstLine = f.readline() # read the first line and throw it out
            data = f.read() # read the rest
            f.seek(0) # set the cursor to the top of the file
            f.write(data) # write the data back
            f.truncate() # set the file size to the current size
            return firstLine
    
    fifo = pop('filename.txt')
    

提交回复
热议问题