python - 如何遍历 zip 文件夹中的文件而不提取它们?
问题描述
我有一个 zip 格式的大型数据集,我无法直接解压缩它,因为我的机器上所需的空间量还远远不够。我正在尝试编写一个程序,该程序将遍历 zip 文件中的文件并在将其复制到另一个文件夹时将其删除。可悲的os.listdir
是,没有帮助,我想知道是否有一个模块zipfile
可以让我这样做?
解决方案
这是一个提供 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 使用。
推荐阅读
- dc.js - dc.js 中的相关矩阵
- flutter - 颤抖,飞镖。如何向地图添加键和值
- reactjs - 在 reactjs 中使用 Sass 和 antdesign
- node.js - Discord JS V13 无法向公会所有者发送消息
- java - Spring SQS @SqsListener 与 BeanPostProcessor
- birt - 如何读取组内的所有详细行并进行一些计算
- html - 如何在 CSS 中制作具有完美圆角边缘的半圆线?
- antlr4 - Lexer 不会因输入错误而出现运行时异常
- reactjs - 在我的反应代码中设置表单状态时 event.target.value 不起作用
- vue.js - 如何导入样式表范围和深度定位子组件?