hruyu
hruyu

Reputation: 43

how to use python to find consecutive lines

I have a file,like this:

the 1 file is:
none
the 2 file is:
a-h-f
the 3 file is:
a-h-p
the 4 file is:
none

I want to use python to know which two consecutive files are contend,not none.Take this file as example,"the 2 file" and "the 3 file" are continuous and have content.The result I expect is:

   the 2 file is:
   a-h-f
   the 3 file is:
   a-h-p

Please someone give me some tips.Thanks.

Upvotes: 1

Views: 557

Answers (2)

Abhijeetk431
Abhijeetk431

Reputation: 846

Make a list of 4 consecutive elements and filter those with none in it. Then party...

with open("input_file","r") as in_file:
    lines = in_file.read().split("\n")
consecutive_lines_4 = [lines[i:i+4] for i in range(0,len(lines)-3),2]
result = [i for i in consecutive_lines_4 if 'none' not in i]
print(result)

Upvotes: 0

fferri
fferri

Reputation: 18950

Put your lines in a list, i.e. could be lines = f.readlines() where f is a file object, or:

lines = '''the 1 file is:
none
the 2 file is:
a-h-f
the 3 file is:
a-h-p
the 4 file is:
none
'''.splitlines()

then:

for t in zip(*[lines[i::2] for i in range(4)]):
    if 'none' not in t:
        # t is ('the 2 file is:', 'a-h-f', 'the 3 file is:', 'a-h-p')
        # do something with it, e.g.:
        for x in t:
            print(x)

prints:

the 2 file is:
a-h-f
the 3 file is:
a-h-p

Upvotes: 1

Related Questions