python - 用python解压目录结构

标签 python unzip

我有一个包含以下目录结构的 zip 文件:

dir1\dir2\dir3a
dir1\dir2\dir3b

我正在尝试解压缩它并维护目录结构,但是我得到了错误:

IOError: [Errno 2] No such file or directory: 'C:\\\projects\\\testFolder\\\subdir\\\unzip.exe'

其中 testFolder 是上面的 dir1,subdir 是 dir2。

有没有快速解压文件和维护目录结构的方法?

最佳答案

如果您使用的是 Python 2.6,则 extract 和 extractall 方法非常有用。我现在必须使用 Python 2.5,所以如果它们不存在,我只需要创建目录。您可以使用 namelist() 方法获取目录列表。目录将始终以正斜杠结尾(即使在 Windows 上),例如,

import os, zipfile

z = zipfile.ZipFile('myfile.zip')
for f in z.namelist():
    if f.endswith('/'):
        os.makedirs(f)

您可能不想完全那样做(即,您可能希望在遍历名称列表时提取 zip 文件的内容),但您会得到想法。

关于python - 用python解压目录结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/639962/

相关文章:

java - Android - 解压SystemUI修改里面的文件

python读取CLOB数据

python - Django migrate error _mysql_exceptions.ProgrammingError : (1064, "你的SQL语法有错误

ant - 解压缩时保留文件权限,并使用ant压缩文件

multithreading - Delphi:Form的线程=“Canvas does not allow drawing”中的ZipForge被卡住

git - ant build - unzip 不支持嵌套的 "cutdirsmapper"元素

python - 我正在尝试在列表中创建列表

python - Pandas:读取文件的头部和中间部分

python - Ubuntu Box 偶尔使用 Twitter API 浪费时间

linux - 无法在 Amazon Linux AMI 中解压缩上传的文件