Search code examples
pythonparsingloopslines

Python - Parsing multiple lines of text from file


I am stuck on a problem I am working on.

It involves opening a file reading a line and then comparing the next two lines in the file to it. Then move down one line, ie second line in the file and then compare the next two lines to it again.

I am having a hard time creating a loop that will go through these steps.

So far I have done this

write_file = input_file[:-3] + "bak"
read_file = input_file

with open(write_file, "w") as write:
    with open(read_file,"r") as read:
        for line in read:
            line1 = line

Thank you.


Solution

  • Something like:

    tri_lines = [lines[i:i+3] for i in range(0,len(lines),3)]
    
    #Then you can iterate through:
    
    For triplet in tri_lines:
         # your code here, compare tri_lines[0] with tri_lines[1] etc.
    

    i'll leave you the task of getting all lines of the file into a list.

    note that you'll need to do some simple validation to handle the cases where the file does not have a number of lines divisible by 3.

    you can even do

    for triplet in [lines[i:i+3] for i in range(0,len(lines),3)]:
        if triplet[0] == triplet[1]:
            #do something
        if triplet[0] == triplet[2]:
            #do something
    

    though this might not be as clear