Python:不同的(excel)文件名,相同的内容ch

2024-05-04 21:01:52 发布

您现在位置:Python中文网/ 问答频道 /正文

问:使用Python,如何测试两个不同名称的Excel文件具有相同的内容?在

我所尝试的:我所看到的大多数答案都表明文件cmp.cmp或者散列。我试过同时使用这两种方法,但没有成功。特别是,假设'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”。在


Tags: 文件方法falsetrue内容readxlsxexcel
1条回答
网友
1楼 · 发布于 2024-05-04 21:01:52

我过去也遇到过同样的问题,最后只是做了一些“逐行”的比较。对于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

它是非常基本的,显然没有考虑样式或格式,但只是为了测试两个文件的文本内容。希望这对某人有帮助。在

相关问题 更多 >