There are 3 files, 2 of them compare the lines inside, information is recorded in the third file, depending on the check for an entry.

f1 = open('text1.txt') f2 = open('text2.txt') f = open('over.txt', 'a') for line1 in f1.readlines(): for line2 in f2.readlines(): if line1 in line2: f.write(line1) break elif line1 not in line2: f.write(line1) elif line2 not in line1: f.write(line2) f.close() f1.close() f2.close() 

If I set break to the first if , I get the output to the first for and no longer enters the second for loop. How best to make the second cycle run?

    1 answer 1

    The problem is that readlines reads all lines from a file and the read position after this method is set to the end of the file, so the next call to readlines returns an empty list. There may be several solutions.


    Solution 1.

    Re-open the second file on each iteration of the first cycle:

     f1 = open('text1.txt') f = open('over.txt', 'a') for line1 in f1.readlines(): f2 = open('text2.txt') # <<<--- for line2 in f2.readlines(): if line1 in line2: f.write(line1) break elif line1 not in line2: f.write(line1) elif line2 not in line1: f.write(line2) f2.close() # <<<--- f.close() f1.close() 

    Solution 2.

    Read all the lines of the second file into a variable and read it in the second cycle:

     f1 = open('text1.txt') f = open('over.txt', 'a') f2 = open('text2.txt') lines2 = f2.readlines() # <<<--- f2.close() for line1 in f1.readlines(): for line2 in lines2: # <<<--- if line1 in line2: f.write(line1) break elif line1 not in line2: f.write(line1) elif line2 not in line1: f.write(line2) f.close() f1.close() 

    Solution 3: Use the seek method, which will move the reading position:

     f1 = open('text1.txt') f2 = open('text2.txt') f = open('over.txt', 'a') for line1 in f1.readlines(): f2.seek(0) # <<<--- for line2 in f2.readlines(): if line1 in line2: f.write(line1) break elif line1 not in line2: f.write(line1) elif line2 not in line1: f.write(line2) f.close() f1.close() f2.close() 


    But the most effective solution that is much more economical is related to resources:

     f1 = open('text1.txt') f2 = open('text2.txt') f = open('over.txt', 'a') for line1 in f1: # <<<--- f2.seek(0) # <<<--- for line2 in f2: # <<<--- if line1 in line2: f.write(line1) break elif line1 not in line2: f.write(line1) elif line2 not in line1: f.write(line2) f.close() f1.close() f2.close() 

    Here, instead of the readlines method, reading the entire file, an iterator will be used, reading the file line by line as necessary.