首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用python比较zip文件中的两个文本文件

使用python比较zip文件中的两个文本文件
EN

Stack Overflow用户
提问于 2022-01-03 18:34:12
回答 1查看 165关注 0票数 0

我希望使用python比较两个名称相同、路径相同的文本文件在两个不同的zip文件中。

我一直在寻找各种各样的方法,但在我的案例中没有找到最有效的解决方案。

我的代码:

代码语言:javascript
复制
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"

此外,即使我硬编码路径,用于比较的文件读取缓冲区总是空的。所以这种比较在这种情况下是行不通的。

我被困在这个奇怪的案例中,任何帮助都是非常感谢的。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-01-03 18:59:14

您应该能够在不使用Path的情况下实现这一点,因为路径是特定于the文件的,并且不需要以特定于os的方式处理。namelist()返回的字符串既可用于比较,也可用作open()的参数,如下所示:

代码语言:javascript
复制
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)))
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70570022

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档