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