使用python比较两个文件内容异同的问题
在网上找到了类似的代码
[Python] 纯文本查看 复制代码 import os
class cmpFile:
def __init__(self, file1, file2):
self.file1 = file1
self.file2 = file2
def fileExists(self):
if os.path.exists(self.file1) and \
os.path.exists(self.file2):
return True
else:
return False
# 对比文件不同之处, 并返回结果
def compare(self):
if cmpFile(self.file1, self.file2).fileExists() == False:
return []
fp1 = open(self.file1.encode('gbk','ignore').decode('gbk'))
fp2 = open(self.file2.encode('gbk','ignore').decode('gbk'))
flist1 = [i for i in fp1]
flist2 = [x for x in fp2]
fp1.close()
fp2.close()
flines1 = len(flist1)
flines2 = len(flist2)
if flines1 < flines2:
flist1[flines1:flines2+1] = ' ' * (flines2 - flines1)
if flines2 < flines1:
flist2[flines2:flines1+1] = ' ' * (flines1 - flines2)
counter = 1
cmpreses = []
for x in zip(flist1, flist2):
if x[0] == x[1]:
counter +=1
continue
if x[0] != x[1]:
cmpres = '%s和%s第%s行不同, 内容为: %s --> %s' % \
(self.file1, self.file2, counter, x[0].strip(), x[1].strip())
cmpreses.append(cmpres)
counter +=1
return cmpreses
if __name__ == '__main__':
print('当前路径:',os.getcwd())
cmpfile = cmpFile('file1.txt', 'file2.txt')
difflines = cmpfile.compare()
print('开始比较...')
for i in difflines:
print(i, end='\n')
但是只能比较txt文件,如果换成word或其他文件,编码就错误了,请问大家:
1.如何解决比较word或excel的问题?
2.有无其他功能更强大或可视化的比较两个文件内容差异的代码?
谢谢! |