Python '==' incorrectly returns false

I am trying to get the difference in two files per line, and Python always returns false; even when I make a difference in the same files, Python (almost) always returns false. Goofy example, but it replicates my problem in Python 3.4.3.

file1.txt (example)
1
2
3

file1 = r"pathtofile\file1.txt"
file2 = r"pathtofile\file1.txt"
f1 = open(file1, "r")
f2 = open(file2, "r")

for line1 in f1:
    found = False
    for line2 in f2:
        if repr(line1) == repr(line2):
            found = True
            print("true")
    if found == False:
        print("false")

Python correctly identifies that the first line is the same, but everything after that is false. Can anyone else repeat this? Any ideas?

+4
source share
3 answers

You have exhausted the iterator after the first iteration over f2, you need file.seek(0)to go back to the beginning of the file.

for line1 in f1:
    found = False
    for line2 in f2:
        if repr(line1) == repr(line2):
            print("true")
    f2.seek(0) # reset pointer to start of file

You check only the first line f1by line f2, after the first loop there is no iteration.

, , break, , , reset found = False .

, , .

with open("f1") as f1, open("f2") as f2:   
    st = set(f1)
    common = st.intersection(f2)

, st.difference(f2), st.symmetric_difference(f2). , .

filecmp difflib

+8

Python , , . , . f2 readlines. , . , .

file1 = r"pathtofile\file1.txt"
file2 = r"pathtofile\file1.txt"
f1 = open(file1, "r")
f2 = open(file2, "r").readlines()

for line1 in f1:
    found = False
    for line2 in f2:
        if repr(line1) == repr(line2):
            print("true")
    if found == False:
        print("false")
+2

, , , , 1- 1- , 2- 1- ..

for-else:

for line1, line2 in zip(f1, f2):
    if line1 != line2:
        print ("false")
        break   # found 2 different lines in the same place so the files can't be equal
else:
     print ("true")
+2

Source: https://habr.com/ru/post/1599350/


All Articles