Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
390 views
in Technique[技术] by (71.8m points)

unzip - Unzipping directory structure with python

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

dir1dir2dir3a
dir1dir2dir3b

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\estFolder\subdir\unzip.exe'

where testFolder is dir1 above and subdir is dir2.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...