Check if directory exists in zip file with Python

I originally thought about using os.path.isdir, but I don't think this works for zip files. Is there a way to look into a zip file and make sure that this directory exists? I would like to prevent using unzip -l "$@"as much as possible, but if this is the only solution, then I think I have no choice.

+5
source share
3 answers

Just check the file name 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 the archive does not explicitly contain a directory; 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
+6
source

You can check directories with ZipFile.namelist () .

import os, zipfile
dir = "some/directory/"

z = zipfile.ZipFile("myfile.zip")
if dir in z.namelist():
    print "Found %s!" % dir
+6

, ZipFile.

import zipfile
z = zipfile.ZipFile("file.zip")

if "DirName/" in [member.filename for member in z.infolist()]:
    print("Directory exists in archive")

Python32.

0

All Articles