我正在编写一段代码,用于比较python中的两个文本文件并打印两者之间的差异。有人告诉我要用套子。是否也可以使用对话框来选择文件,而不是手动输入文件名?我是python的初学者,所以如果你能写出代码,我会非常感激。
文件1.text
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 ()
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()
一个更简单的解决方案,使用内置的集合功能:
a = set(['hamburgers', 'potatoes', 'avocado', 'grapes', 'seaweed'])
b = set(['cheeseburgers', 'potatoes', 'peanuts', 'grapes', 'seaweed'])
a.difference(b)
b.difference(a)
函数set.difference()再次为您提供集合对象,您可以根据需要对其进行处理。[我希望我不是在为你解决家庭作业问题…]
以下解决方案符合我的确切要求。
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