gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:56:18 25 4
gpt4 key购买 nike

我正在编写一个代码,该代码可以在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com