How to delete the first line of a text file?

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.

Leave a Comment