-3

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.

Vlad
  • 932
  • 6
  • 18
  • 2
    This is a Question and Answer site not a site for general tutorials, examples and tips. Please read the help: http://stackoverflow.com/help/on-topic before posting or you will get voted down. – Matt Coubrough Nov 27 '14 at 05:13
  • Users are supposed to vote down all questions that show no Research effort. Have you tried searching for "looping in python", or even done the basic tutorials on the python site? – Matt Coubrough Nov 27 '14 at 05:24

2 Answers2

1

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

user2782067
  • 382
  • 4
  • 19
1

Like @Matt Coubrough said, this isn't a QnA forum. You should try to solve the problem yourself before coming here expecting someone to solve your question for you.

In an effort to get you on the right track, here is some pseudocode

//NOTE: This pseudocode assumes there are atleast 3 lines in the file
line1 = file.getLine()
line2 = file.getLine()
line3 = file.getLine()
//compare line1, line2, and line3

while(fileIsNotEmpty) {
    line1 = line2
    line2 = line3
    line3 = file.getLine()
    //compare line1, line2, and line3
}
David.Jones
  • 1,413
  • 8
  • 16