使用Python检查zip文件中是否存在目录 [英] Check if a directory exists in a zip file with Python
本文介绍了使用Python检查zip文件中是否存在目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
最初我想使用 os.path.isdir
但我认为这不适用于 zip 文件.有没有办法查看 zip 文件并验证此目录是否存在?我想尽可能避免使用 unzip -l "$@"
,但如果这是唯一的解决方案,那么我想我别无选择.
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.
推荐答案
只需检查文件名末尾的/"即可.
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
这篇关于使用Python检查zip文件中是否存在目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文