Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a directory exists in a zip file with Python

Tags:

python

unzip

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.

like image 751
Stupid.Fat.Cat Avatar asked Jul 23 '12 17:07

Stupid.Fat.Cat


People also ask

How do I check if a directory exists in Python?

os. path. isdir() method in Python is used to check whether the specified path is an existing directory or not. This method follows a symbolic link, which means if the specified path is a symbolic link pointing to a directory then the method will return True.

How do you check if a file is a ZIP file in Python?

isdir() or a file with TarInfo. isfile() . Similarly you can determine whether a file is a zip file using zipfile. is_zipfile() .

What is Zipfile in Python?

Python's zipfile is a standard library module intended to manipulate ZIP files. This file format is a widely adopted industry standard when it comes to archiving and compressing digital data.

Which of the following can be used to check whether a file exists or not?

os. path. isfile() checks whether a file exists. Both of these methods are part of the Python os library.


2 Answers

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
like image 87
Igor Chubin Avatar answered Oct 15 '22 08:10

Igor Chubin


You can check for the directories with ZipFile.namelist().

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

z = zipfile.ZipFile("myfile.zip")
if dir in z.namelist():
    print "Found %s!" % dir
like image 45
enderskill Avatar answered Oct 15 '22 08:10

enderskill