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

Question:

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 😛

Asked By: Dreamsies

||

Answers:

Unfortunately, I think you have to open the file, read it, delete the lines, rewrite the file. So I’d do something like this:

def delete_lines(file, delete_lines=[]):
    with open(file, "r") as f:
        lines = f.readlines()
    for line in delete_lines:
        if line < len(lines):
            lines[line] = ""
    with open(file, "w") as f:
        f.writelines(lines)


delete_lines(r"/my_path/to/file", delete_lines=[0, 5, 7])

Not that there is any significant difference, but alternatively, you can join the lines together and write it as a string:

def delete_lines(file, delete_lines=[]):
    with open(file, "r") as f:
        lines = f.readlines()
    for line in delete_lines:
        if line < len(lines):
            lines[line] = ""
    with open(file, "w") as f:
        f.write("".join(lines))


delete_lines(r"/my_path/to/file", delete_lines=[0, 5, 7])

Here is some sample data:

abc
def
ghi
jkl
mno
pqr
stu
vwx
yz1
234
567
890
098
765
543
21z
yxw
etc
etc
etc

and its output to the file

def
ghi
jkl
mno
stu
yz1
234
567
890
098
765
543
21z
yxw
etc
etc
etc

EDIT to meet the criteria for the OP:

def delete_lines(file, max_history=15):
    with open(file, "r") as f:
        lines = f.readlines()
    if len(lines) > max_history:
        del lines[max_history + 1:]
        del lines[0]
    with open(file, "w") as f:
        f.writelines(lines)


delete_lines(r"/my_path/to/file")
Answered By: Shmack

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!)

Answered By: Valentin Goldité
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.