Joe Smart
Joe Smart

Reputation: 763

Removing the second line from a text file

I have read a few questions that are similar to this, but all are either removing the first or last line or are removing a line that matches (or doesn't match) a specified string.

What I want to do is to remove the 2nd line in a text file and then move everything up by one line rather than filling the 2nd line with whitespace.

Eg. line 3 becomes line 2, line 4 becomes line 3 etc.

for example, if my input was:

1
2
3
4
5

I would want the output to be:

1
3
4
5

I can't just specify to delete a line if it matches a string as the 2nd line changes daily based on the date.

I have started off using

with open('file.txt', 'r') as f:
    lines = f.readlines()
    f.write(lines)

But I can't work out how to change that to skip the 2nd line.

Context:

This is for generating a rota for my team at work. The first line is a header and the 2nd line is the most recent date. Which means that at midnight every night the 2nd line becomes yesterday, at that point I need to remove that line and add a new line at the end, but that part is easier.

Upvotes: 1

Views: 3499

Answers (2)

open source guy
open source guy

Reputation: 2787

ff = open("messi.txt",'w')
with open('d.txt', 'r') as f:
    lines = f.readlines()
    lines.pop(1)
    ff.writelines(lines)

Upvotes: 0

Germano
Germano

Reputation: 2482

You have to read the file and then rewrite it with the lines you want. For example:

lines = []

with open('file.txt', 'r') as f:
    lines = f.readlines()

with open('file.txt', 'w') as f:
    f.writelines(lines[:1] + lines[2:]) # This will skip the second line

This is a viable approach as long as you deal with small files. Otherwise you'd better read from one file and write to another one.

Upvotes: 5

Related Questions