How to delete the first line of a text file?

Safer to use one open() for read & write, so you won't lose data 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')

Here is a memory-efficient (?) solution which makes use of shutil:

import shutil

source_file = open('file.txt', 'r')
source_file.readline()
# this will truncate the file, so need to use a different file name:
target_file = open('file.txt.new', 'w')

shutil.copyfileobj(source_file, target_file)

You can do it much easier by simply stating what is the first line to be read:

    with open(filename, "r") as f:
        rows = f.readlines()[1:]

Assuming you have enough memory to hold everything in memory:

with open('file.txt', 'r') as fin:
    data = fin.read().splitlines(True)
with open('file.txt', 'w') as fout:
    fout.writelines(data[1:])

We could get fancier, opening the file, reading and then seeking back to the beginning eliminating the second open, but really, this is probably good enough.

Tags:

Python

File