Unzipping directory structure with python

后端 未结 9 1661
闹比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:11

    I tried this out, and can reproduce it. The extractall method, as suggested by other answers, does not solve the problem. This seems like a bug in the zipfile module to me (perhaps Windows-only?), unless I'm misunderstanding how zipfiles are structured.

    testa\
    testa\testb\
    testa\testb\test.log
    > test.zip
    
    >>> from zipfile import ZipFile
    >>> zipTest = ZipFile("C:\\...\\test.zip")
    >>> zipTest.extractall("C:\\...\\")
    Traceback (most recent call last):
      File "", line 1, in 
      File "...\zipfile.py", line 940, in extractall
      File "...\zipfile.py", line 928, in extract
      File "...\zipfile.py", line 965, in _extract_member
    IOError: [Errno 2] No such file or directory: 'C:\\...\\testa\\testb\\test.log'
    

    If I do a printdir(), I get this (first column):

    >>> zipTest.printdir()
    File Name
    testa/testb/
    testa/testb/test.log
    

    If I try to extract just the first entry, like this:

    >>> zipTest.extract("testa/testb/")
    'C:\\...\\testa\\testb'
    

    On disk, this results in the creation of a folder testa, with a file testb inside. This is apparently the reason why the subsequent attempt to extract test.log fails; testa\testb is a file, not a folder.

    Edit #1: If you extract just the file, then it works:

    >>> zipTest.extract("testa/testb/test.log")
    'C:\\...\\testa\\testb\\test.log'
    

    Edit #2: Jeff's code is the way to go; iterate through namelist; if it's a directory, create the directory. Otherwise, extract the file.

提交回复
热议问题