Python'=='错误地返回false [英] Python '==' incorrectly returning false

查看:36
本文介绍了Python'=='错误地返回false的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图逐行获取两个文件的差异,而 Python 总是返回 false;即使我对相同的文件进行比较,Python(几乎)总是返回 false.愚蠢的例子,但它在 Python 3.4.3 上复制了我的问题.

I'm trying to get a difference of two files line by line, and Python is always returning false; even when I do a diff of the same files, Python (almost) always returns false. Goofy example, but it replicates my 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")

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 正确识别出第一行是相同的,但之后的所有内容都是错误的.其他人可以复制这个吗?有什么想法吗?

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

推荐答案

f2 的第一次迭代后你已经用完了迭代器,你需要 file.seek(0)代码>返回到文件的开头.

You have exhausted the iterator after the first iteration over f2, you need to file.seek(0) to go back to the start 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

你只检查 f1 的第一行和 f2 的行,在第一个循环之后没有什么可迭代的.

You only check the first line of f1 against the lines of f2, after the first loop there is nothing to iterate over.

根据您想要发生的情况,您要么需要在找到匹配的行时break,要么在内循环中重置 found = False.

Depending on what you want to happen, you either need to break when you find the line that matches or else reset found = False in the inner loop.

如果你想要所有匹配的行,那么只需将输出存储在一个列表中,或者如果文件不是很大,你可以使用集合来查找公共行.

If you want all the matching lines then just store the output in a list or if the files are not very big you can use sets to find to find common lines.

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

如果您想要差异,请使用 st.difference(f2),对于两者中的行,两者都使用 st.symmetric_difference(f2).这完全取决于你真正想要做什么.

If you want the difference use st.difference(f2), for lines in either both not in both use st.symmetric_difference(f2). It all depends on what you actually want to do.

您可能还想查看 filecmpdifflib

You might also want to check out filecmp and difflib

这篇关于Python'=='错误地返回false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆