我有一个 zip 格式的大型数据集,但无法直接解压缩它,因为我的计算机上的空间远远不够。我正在尝试编写一个程序,该程序将迭代 zip 文件内的文件,并在将其复制到另一个文件夹时删除它们。可悲的是,
os.listdir
没有任何帮助,我想知道zipfile
中是否有一个模块可以让我做到这一点?
以下链接提供了 Linux/MacOs 命令,用于在不解压的情况下查看 zip 文件的内容:无需解压即可读取内容
您可以使用 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 使用。
使用
zipfile.Path("your_zip.zip").iterdir()
- https://docs.python.org/3/library/zipfile.html#zipfile.Path.iterdir
from pathlib import Path
import zipfile
def test_iter_zip(tmp_path):
dummy_files = ["1.txt", "2.txt", "3.txt"]
[Path(f"{tmp_path}{dummy_file}").touch() for dummy_file in dummy_files]
with zipfile.ZipFile(f"{tmp_path}_zip.zip", "w") as archive:
for dummy_file in dummy_files:
archive.write(f"{tmp_path}{dummy_file}", dummy_file)
# Now that the zip is created. There is how you can use the iterdir() to iterate the zip's file.
zip_files = [file.name for file in zipfile.Path(f"{tmp_path}_zip.zip").iterdir()]
for dummy_file in dummy_files:
assert dummy_file in zip_files