Search code examples
pythonunzip

Check if a directory exists in a zip file with Python


Initially I was thinking of using os.path.isdir but I don't think this works for zip files. Is there a way to peek into the zip file and verify that this directory exists? I would like to prevent using unzip -l "$@" as much as possible, but if that's the only solution then I guess I have no choice.


Solution

  • Just check the filename with "/" at the end of it.

    import zipfile
    
    def isdir(z, name):
        return any(x.startswith("%s/" % name.rstrip("/")) for x in z.namelist())
    
    f = zipfile.ZipFile("sample.zip", "r")
    print isdir(f, "a")
    print isdir(f, "a/b")
    print isdir(f, "a/X")
    

    You use this line

    any(x.startswith("%s/" % name.rstrip("/")) for x in z.namelist())
    

    because it is possible that archive contains no directory explicitly; just a path with a directory name.

    Execution result:

    $ mkdir -p a/b/c/d
    $ touch a/X
    $ zip -r sample.zip a
    adding: a/ (stored 0%)
    adding: a/X (stored 0%)
    adding: a/b/ (stored 0%)
    adding: a/b/c/ (stored 0%)
    adding: a/b/c/d/ (stored 0%)
    
    $ python z.py
    True
    True
    False