更新时间:2022-05-03 01:33:34
只需检查文件名末尾的/"即可.
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")
你用这条线
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.
执行结果:
$ 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