Python:不同(Excel)文件名,相同内容检查
问:使用Python,怎么测试两个不同名字的Excel文件内容是否一样?
我尝试过的:我看到的大部分答案都建议用filecmp.cmp或者hash。我试过这两种方法,但都没有成功。比如说,假设'f1.xlsx'文件里只有两个非空单元格:A1 = 'hello'和B1 = 'world'。然后,我把这些内容复制到一个新文件'f2.xlsx'里。现在这两个文件在同样的位置都有两个非空的内容。我得到的结果是:
>> f1 = 'f1.xlsx'
>> f2 = 'f2.xlsx'
#Using read():
>>> open(f1).read()==open(f2).read()
False
#Using filecmp.cmp:
>>> filecmp.cmp(f1, f2, shallow=True)
False
#Using izip:
>>> all(line1 == line2 for line1, line2 in izip_longest(f1, f2))
False
#Using hash:
>>> hash1=hashlib.md5()
>>> hash1.update(f1)
>>> hash1 = hash1.hexdigest()
>>> hash2=hashlib.md5()
>>> hash2.update(f2)
>>> hash2 = hash2.hexdigest()
>>> hash1==hash2
False
#also note, using getsize:
>>> os.path.getsize(f1)
8007
>>> os.path.getsize(f2)
8031
当然,我可以用Pandas把Excel文件当作数据框来处理,然后用像all()这样的标准比较方法返回True,但我希望能有更好的方法,比如也能适用于.docx文件。
提前谢谢大家!我怀疑问题出在像.xlsx或.docx这样的扩展名在“标准”测试中的使用,但我希望还是能找到一种有效的方法来比较内容。
注意:如果能简化问题,顺序不重要,也就是说如果f2的A1是'world',B1是'hello',我希望返回“True”。
1 个回答
0
我以前也遇到过同样的问题,最后我只是逐行对比了一下。对于Excel文件,我使用了openpyxl这个模块,它提供了一个很好的界面,可以逐个单元格地查看文件内容。对于docx文件,我用了python_docx模块。以下的代码对我来说是有效的:
>>> from openpyxl import load_workbook
>>> from docx import Document
>>> f1 = Document('testDoc.docx')
>>> f2 = Document('testDoc.docx')
>>> wb1 = load_workbook('testBook.xlsx')
>>> wb2 = load_workbook('testBook.xlsx')
>>> s1 = wb1.get_active_sheet()
>>> s2 = wb2.get_active_sheet()
>>> def comp_xl(s1, s2):
>>> for row1, row2 in zip(s1.rows, s2.rows):
>>> for cell_1, cell_2 in zip(row1, row2):
>>> if isinstance(cell_1, openpyxl.cell.cell.MergedCell):
>>> continue
>>> elif not cell_1.value == cell_2.value:
>>> return False
>>> return True
>>> comp_xl(s1, s2)
True
>>> all(cell_1.value==cell_2.value for cell_1, cell_2 in zip((row for row in s1.rows), (row for row in s2.rows)) if isinstance(cell_1, openpyxl.cell.cell.Cell))
True
>>> def comp_docx(f1, f2):
>>> p1 = f1.paragraphs
>>> p2 = f2.paragraphs
>>> for i in range(len(p1)):
>>> if p1[i].text == p2[i].text:
>>> continue
>>> else: return False
>>> return True
>>> comp_docx(f1, f2)
True
>>> all(line1.text == line2.text for line1, line2 in zip(f1.paragraphs, f2.paragraphs))
True
这个方法很简单,显然没有考虑到样式或格式,但如果只是想测试两个文件的文本内容,这个方法是可以用的。希望这对某些人有帮助。