Search code examples
pythontext-files

How can I delete the first line in a text file when the file reaches a certain number of lines?


The main part of this question is how can I do something similar to:

    if len(file) > 15:
        completely delete the first line in file
        make sure everything moved up by 1 so that line 16 becomes line 15

so this way when the file reaches 16 lines it will delete the first line completely and push everything up by 1 so that it will always only have 15 lines, think of it as a history timeline (in my specific situation it is being used as a game history storage file)

I hope i managed to explain everything properly, it's my first time using stackoverflow as i'm quite new to coding :P


Solution

  • With only one open:

    with open('text.txt', 'r+', encoding='utf-8') as txt_file:
        lines = txt_file.readlines()
        txt_file.seek(0)
        if len(lines) > 15:
            for i, line in enumerate(lines):
                if 1 <= i <= 15:
                    txt_file.write(line)
            txt_file.truncate()
    

    If you have more than 16 lines in your file, it will remove the lines after the 16th.

    Explanations:

    • 'r+' is a mode allowing you to read and write the document
    • txt_file.seek(0) set the pointer at the beginning of the file for writting instead of the end.
    • txt_file.truncate() delete the end of the file (after the last write)

    For instance:

    1st line
    2nd line
    3rd line
    4th line
    5th line
    6th line
    7th line
    8th line
    9th line
    10th line
    11th line
    12th line
    13th line
    14th line
    15th line
    16th line
    17th line
    18th line
    

    Is changed to:

    2nd line
    3rd line
    4th line
    5th line
    6th line
    7th line
    8th line
    9th line
    10th line
    11th line
    12th line
    13th line
    14th line
    15th line
    16th line
    

    If you want to keep the last lines you can remove <= 15 (but keep the truncation to avoid having 2 times the last line!)