查找python中两个文件之间的差异
我正在编写一段代码,比较python中的两个文本文件,并打印它们之间的差异。我被告知要使用电视机。是否也可以使用对话框来选择文件,而不是手动输入文件名?我是python的初学者,如果你能写出代码,我将非常感激 File1.txt查找python中两个文件之间的差异,python,compare,Python,Compare,我正在编写一段代码,比较python中的两个文本文件,并打印它们之间的差异。我被告知要使用电视机。是否也可以使用对话框来选择文件,而不是手动输入文件名?我是python的初学者,如果你能写出代码,我将非常感激 File1.txt hamburgers potatoes avocado grapes seaweed File2.txt cheeseburgers potatoes peanuts grapes seaweed 所以我想把代码打印出来 芝士汉堡、花生 这是我所拥有的,但不确定是否
hamburgers
potatoes
avocado
grapes
seaweed
File2.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 ()
更简单的解决方案,使用内置的设置功能:
a = set(['hamburgers', 'potatoes', 'avocado', 'grapes', 'seaweed'])
b = set(['cheeseburgers', 'potatoes', 'peanuts', 'grapes', 'seaweed'])
a.difference(b)
b.difference(a)
函数的作用是:再次设置对象,您可以根据需要处理这些对象。
[我希望我没有为你解决家庭作业问题…]下面的解决方案符合我的确切要求
f1=open((os.getcwd()) + "\\Test1.txt","r")
f2=open((os.getcwd()) + "\\Test2.txt","r")
for i, j in zip(f1, f2):
if i != j:
print(i.rstrip() + "\t" + j.rstrip())
f1.close()
f2.close()
输出:
R[10]=0x8 R[10]=0x13
R[54]=0x6 R[54]=0x4
R[59]=0x18 R[59]=0x58
R[60]=0x3d R[60]=0x4c
R[126]=0x59 R[126]=0xbd
您得到了什么输出?请记住,OP,这是非常低效的,尤其是对于大文件。
R[10]=0x8 R[10]=0x13
R[54]=0x6 R[54]=0x4
R[59]=0x18 R[59]=0x58
R[60]=0x3d R[60]=0x4c
R[126]=0x59 R[126]=0xbd