Python '==' incorrectly returning false -
i'm trying difference of 2 files line line, , python returning false; when diff of same files, python (almost) returns false. goofy example, replicates problem on 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") line1 in f1: found = false line2 in f2: if repr(line1) == repr(line2): found = true print("true") if found == false: print("false")
python correctly identifies first line same, after false. can else replicate this? ideas?
you have exhausted iterator after first iteration on f2
, need file.seek(0)
go start of file.
for line1 in f1: found = false line2 in f2: if repr(line1) == repr(line2): print("true") f2.seek(0) # reset pointer start of file
you check first line of f1
against lines of f2
, after first loop there nothing iterate over.
depending on want happen, either need break
when find line matches or else reset found = false
in inner loop.
if want matching lines store output in list or if files not big can use sets find find common lines.
with open("f1") f1, open("f2") f2: st = set(f1) common = st.intersection(f2)
if want difference use st.difference(f2)
, lines in either both not in both use st.symmetric_difference(f2)
. depends on want do.
Comments
Post a Comment