我希望使用python比较两个名称相同、路径相同的文本文件在两个不同的zip文件中。
我一直在寻找各种各样的方法,但在我的案例中没有找到最有效的解决方案。
我的代码:
from zipfile import ZipFile
from pathlib import Path
with ZipFile(zip_path1) as z1, ZipFile(zip_path2) as z2:
file1_paths = [Path(filepath) for filepath in z1.namelist()]
file12_paths = [Path(filepath) for filepath in z12.namelist()]
cmn = list(set(file1_paths ).intersection(set(file12_paths )))
common_files = [filepath for filepath in cmn if str(filepath).endswith(('.txt', '.sh'))]
for f in common_files:
with z1.open(f, 'r') as f1, z2.open(f, 'r') as f2:
if f1.read() != f2.read(): # Also used io.TextIOWrapper(f1).read() here
print('Difference found for {filepath}'.format(filepath=str(f))注意:
我在这里使用了路径库。在行with z1.open(f, 'r')...中,如果我使用路径库路径而不是硬编码路径,我将得到<class 'KeyError'>: "There is no item named WindowsPath('SomeFolder/somefile.txt') in the archive"。
此外,即使我硬编码路径,用于比较的文件读取缓冲区总是空的。所以这种比较在这种情况下是行不通的。
我被困在这个奇怪的案例中,任何帮助都是非常感谢的。
发布于 2022-01-03 18:59:14
您应该能够在不使用Path的情况下实现这一点,因为路径是特定于the文件的,并且不需要以特定于os的方式处理。namelist()返回的字符串既可用于比较,也可用作open()的参数,如下所示:
from zipfile import ZipFile
with ZipFile(zip_path1) as z1, ZipFile(zip_path2) as z2:
common_files = [x for x in set(z1.namelist()).intersection(set(z2.namelist())) if x.endswith('.txt') or x.endswith('.sh')]
# print(common_files)
for f in common_files:
with z1.open(f) as f1, z2.open(f) as f2:
if f1.read() != f2.read():
print('Difference found for {filepath}'.format(filepath=str(f)))https://stackoverflow.com/questions/70570022
复制相似问题