首页 > 解决方案 > 如何遍历 zip 文件夹中的文件而不提取它们?

问题描述

我有一个 zip 格式的大型数据集,我无法直接解压缩它,因为我的机器上所需的空间量还远远不够。我正在尝试编写一个程序,该程序将遍历 zip 文件中的文件并在将其复制到另一个文件夹时将其删除。可悲的os.listdir是,没有帮助,我想知道是否有一个模块zipfile可以让我这样做?

标签: pythonzipzipfile

解决方案


这是一个提供 Linux/MacOs 命令的链接,用于在不解压缩的情况下查看 zip 文件的内容:Read contents without unzipping

您可以使用 os.system(它基本上通过 python 脚本执行终端命令)来获取 zip 的内容。该链接提供unzip -l archive.zip在不解压缩的情况下列出文件。您还可以使用unzip -c archive.zip来获取文件的内容。

这将列出文件而不在终端中解压缩

import os
os.system(unzip -l archive.zip) 

如果要获取列表中的文件名以供 python 脚本使用,请尝试以下操作:

# import this module (available with vanilla python install)
import subprocess

# calls command and pipes results
process = subprocess.Popen(['unzip -c archive.zip'], shell=True, stdout=subprocess.PIPE)

# unpacks the results into a list
files = process.communicate()[0]
files = files.decode()
files = files.split("\n")

这使用子进程模块和 Popen 函数通过终端运行命令并管道返回以供 python 使用。


推荐阅读