python - 在python中查找两个文件之间的差异

标签 python compare

我正在编写一个代码,该代码可以在 python 中比较两个文本文件并打印两者之间的差异。有人告诉我要使用套装。是否也可以有一个对话框来选择文件,而不是手动输入文件名?我对 python 非常初级,所以如果你能写出代码,我将非常感激。

文件1.txt

hamburgers
potatoes
avocado
grapes
seaweed

文件2.txt

cheeseburgers
potatoes
peanuts
grapes
seaweed

所以我想要打印代码 芝士汉堡、花生

这是我所拥有的,但不确定它是否正确:

old_path = 'File1.txt'
new_path = 'File2.txt'

old_lines = file(old_path).read().split('\n')
new_lines = file(new_path).read().split('\n')

old_lines_set = set(old_lines)
new_lines_set = set(new_lines)

old_added = old_lines_set - new_lines_set
old_removed = new_line_set - old_lines_set

for line in old_lines:
    if line in old_added:
        print '-' , line.strip()
    elif line in old_removed:
        print '+' , line.strip()

for line in new_lines:
    if line in old added:
        print '-' , line.strip()
    elif line in old_removed:
        print '+' , line.strip ()

最佳答案

doc = open(filename, 'r')
doc1 = open(filename, 'r')

f1 = [x for x in doc.readlines()]
f2 = [x for x in doc1.readlines()]

diff = [line for line in f1 if line not in f2] # lines present only in f1
diff1 = [line for line in f2 if line not in f1] # lines present only in f2

doc.close()
doc1.close()

关于python - 在python中查找两个文件之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37065030/

相关文章:

python - 如何在 Python (2.7 +) 中等待 ENTER 键按下?

python - 如何让python只显示可整除的数字

python - 如何在 Django 中序列化后构建对象

floating-point - 如何在处理负零时有效地比较两个浮点值的符号

x86 - 如何比较 x86 中的地址

image - 在 C++ 中使用 OpenCV 删除背景

python - 如何在 selenium webdriver (python) 中禁用 chrome 的 "save password"弹出窗口

python - 将带有变量名称的字符串转换为字典

python - 为什么在比较Python对象元组时先调用__eq__,然后调用__cmp__?

java - 比较运算符自定义对象java