如何使用 Python 从 .zip 中解压缩特定文件夹

新手上路,请多包涵

我希望从 .zip 中的 Python 中解压缩特定文件夹:

eg archive.zip contains the folders foo and bar , I want to unzip foo to a specific location, retaining it’s folder structure.

原文由 James 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 482
2 个回答

检查 zipfile 模块。

对于你的情况:

 import zipfile

archive = zipfile.ZipFile('archive.zip')

for file in archive.namelist():
    if file.startswith('foo/'):
        archive.extract(file, 'destination_path')

原文由 kaspersky 发布,翻译遵循 CC BY-SA 4.0 许可协议

你应该拉上你的拉链….


 import zipfile

archive = zipfile.ZipFile('archive.zip')

for file in archive.namelist():
    if file.startswith('foo/'):
        archive.extract(file, 'destination_path')

archive.close()

或者只是使用更安全的方法。随着将关闭你的拉链。

 import zipfile
with zipfile.ZipFile('archive.zip') as archive:
    for file in archive.namelist():
        if file.startswith('foo/'):
            archive.extract(file, 'destination_path')

原文由 Hildermes José Medeiros Filho 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏