用python解压目录结构 [英] Unzipping directory structure with python

查看:26
本文介绍了用python解压目录结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a zip file which contains the following directory structure:

dir1\dir2\dir3a
dir1\dir2\dir3b

我正在尝试解压缩它并维护目录结构,但出现错误:

I'm trying to unzip it and maintain the directory structure however I get the error:

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

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

where testFolder is dir1 above and subdir is dir2.

有没有快速解压文件并保持目录结构的方法?

Is there a quick way of unzipping the file and maintaining the directory structure?

推荐答案

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

The extract and extractall methods are great if you're on Python 2.6. I have to use Python 2.5 for now, so I just need to create the directories if they don't exist. You can get a listing of directories with the namelist() method. The directories will always end with a forward slash (even on Windows) e.g.,

import os, zipfile

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

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

You probably don't want to do it exactly like that (i.e., you'd probably want to extract the contents of the zip file as you iterate over the namelist), but you get the idea.

这篇关于用python解压目录结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆