Loïs Veillat
Loïs Veillat

Reputation: 1

Delete a line and its previous line from file

I have the following file:

>Line1
Some contents of line 1
>Line2
------Some contents I don't need
>Line3
More content of line 3

I try to delete the lines starting with --- as well as the previous line, which would give as result:

>Line1
Some contents of line 1
>Line3
More content of line 3

Here is my current code, for the moment I can only delete the lines starting with --- but not the line which precedes it:

with open("test.txt") as f1:
    for lines in f1:
        if lines.startswith("---"):
            pass
        else:
            print(lines)

Upvotes: 0

Views: 80

Answers (4)

Tomerikoo
Tomerikoo

Reputation: 19403

You can use the grouper function from the itertools Recipes page:

from itertools import zip_longest

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)

Using that function to iterate the lines from the file in couples, the main code becomes very compact and simple:

with open("test.txt") as f:
    for lines in grouper(f, 2, fillvalue=''):
        if not lines[1].startswith("---"):
            print(*lines, sep='', end='')

Which will print with your example file:

>Line1
Some contents of line 1
>Line3
More content of line 3

Upvotes: 0

kaouther
kaouther

Reputation: 359

Here is a suggestion :

with open ("test.txt") as f:
   line1 = f.readline()
   while line1:
      line2 = f.readline()
      if not line2.startswith("---"):
         print(line1,"\n",line2)
      line1 = f.readline()

Upvotes: 0

Kaligule
Kaligule

Reputation: 754

This is the most readable solution I could come up with.

with open("test.txt") as lines:
    # initial value (relevant for first line only)
    last_line = next(lines)
    last_line_started_with_dashes = False

    for line in lines:
        this_line_starts_with_dashes = line.startswith("---")

        if not (last_line_started_with_dashes or this_line_starts_with_dashes):
            print(last_line)

        # prepare for next iteration
        last_line_started_with_dashes = this_line_starts_with_dashes
        last_line = line

Upvotes: 0

Andrej Kesely
Andrej Kesely

Reputation: 195418

You can try this script to not print the line that starts with --- and the line before it:

with open("file.txt", "r") as f1:
    i = map(str.strip, f1)
    prev_line = next(i)
    for line in i:
        if line.startswith('---'):
            prev_line = next(i, '')
            continue
        print(prev_line)
        prev_line = line
    print(prev_line)

Upvotes: 1

Related Questions