speedomes
speedomes

Reputation: 23

Return the next 4 lines after a match has been found

Hope you guys can help. I am currently learning python and stumped by this challenge I have set myself.

I have a file1 with approx 1000 lines of text like this:

1 6  
4 6  
1 4  
2 4  
1 5  
4 6  
3 6  
1 3  
2 4  
..etc etc

I have another file2 with 4 (or more) lines of text like this:

4 6  
1 4  
2 4  
1 5  

I am trying to find the exact match in file1 with the 4 lines of text in file2 and then return the next 4 lines that follow the match in file1. So in the above example, the return would read:

4 6  
3 6  
1 3  
2 4  

The problem I am having is trying to search for the 4 lines in file1. A single file is easy. I am thinking it will be done using loops but the more I try the cloudier my head becomes!

The closest I have come is this code:

textfile = ('results.txt', 'wt')
file1 = open("small_sample.txt", "r")
file2 = open("demo.txt", "r")
file3 = open("results.txt", "a")
list1 = file1.readlines()
list2 = file2.readlines()
file3.write("The following entries appear in both lists: \n")
for i in list1:
    for j in list2:
        if i==j:
            file3.write(i)

Upvotes: 1

Views: 86

Answers (1)

kederrac
kederrac

Reputation: 17322

you can use:

with  open('file1.txt', 'r') as fp:
    t1 = '\n'.join(l.strip() for l in fp.readlines()) # eliminate extra spaces

with  open('file2.txt', 'r') as fp:
    t2 = '\n'.join(l.strip() for l in fp.readlines())


one_row_length = len(t1.split('\n', 1)[0]) + 1 # 1 represents \n new line character
how_many_rows_after = 4 * one_row_length
end_first_match = t1.index(t2) + len(t2) + 1
print(t1[end_first_match : end_first_match + how_many_rows_after])

output:

4 6
3 6
1 3
2 4

Upvotes: 1

Related Questions