Unzipping directory structure with python

后端 未结 9 1648
闹比i
闹比i 2020-12-13 00:56

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

dir1\\dir2\\dir3a
dir1\\dir2\\dir3b

I\'m trying to unzip it and maintai

9条回答
  •  北海茫月
    2020-12-13 01:16

    Note that zip files can have entries for directories as well as files. When creating archives with the zip command, pass the -D option to disable adding directory entries explicitly to the archive. When Python 2.6's ZipFile.extractall method runs across a directory entry, it seems to create a file in its place. Since archive entries aren't necessarily in order, this causes ZipFile.extractall to fail quite often, as it tries to create a file in a subdirectory of a file. If you've got an archive that you want to use with the Python module, simply extract it and re-zip it with the -D option. Here's a little snippet I've been using for a while to do exactly that:

    P=`pwd` && 
    Z=`mktemp -d -t zip` && 
    pushd $Z && 
    unzip $P/.zip && 
    zip -r -D $P/.zip . && 
    popd && 
    rm -rf $Z
    

    Replace .zip and .zip with real filenames relative to the current directory. Then just copy the whole thing and paste it into a command shell, and it will create a new archive that's ready to rock with Python 2.6. There is a zip command that will remove these directory entries without unzipping but IIRC it behaved oddly in different shell environments or zip configurations.

提交回复
热议问题