检查带有Python的zip文件中是否存在目录

Stu*_*Cat 9 python unzip

最初我在考虑使用,os.path.isdir但我不认为这适用于zip文件.有没有办法窥视zip文件并验证该目录是否存在?我想unzip -l "$@"尽可能地防止使用,但如果这是唯一的解决方案,那么我想我别无选择.

Igo*_*bin 8

只需检查文件名末尾的"/"即可.

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")
Run Code Online (Sandbox Code Playgroud)

你用这条线

any(x.startswith("%s/" % name.rstrip("/")) for x in z.namelist())
Run Code Online (Sandbox Code Playgroud)

因为存档可能没有明确包含目录; 只是一个目录名称的路径.

执行结果:

$ 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
Run Code Online (Sandbox Code Playgroud)


end*_*ill 6

您可以使用ZipFile.namelist()检查目录.

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

z = zipfile.ZipFile("myfile.zip")
if dir in z.namelist():
    print "Found %s!" % dir
Run Code Online (Sandbox Code Playgroud)