Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to identify whether an item inside ZipFile is a directory

Consider a zip file that contains a directory with some files inside, e.g. contents of sample.zip are:

Archive:  ziptest.zip
  Length      Date    Time    Name
---------  ---------- -----   ----
        0  03-28-2022 21:00   ziptest/
        0  03-28-2022 21:00   ziptest/folderA/
        0  03-28-2022 21:00   ziptest/folderB/
        0  03-28-2022 21:00   ziptest/folderA/file1.txt
        0  03-28-2022 21:00   ziptest/folderB/file2.txt
---------                     -------
        0                     5 files

How does one distinguish files from directories in Python? (perhaps ignoring this)

from zipfile import ZipFile

archive = ZipFile("ziptest.zip")
print(archive.namelist())
# ['ziptest/', 'ziptest/folderA/', 'ziptest/folderB/', 'ziptest/folderA/file1.txt', 'ziptest/folderB/file2.txt']

One way is to assume that files are the ones that have an extension, but that isn’t always the case. I tried wrapping elements of .namelist() in pathlib.Path, but that doesn’t work. Also, one could look at file size to distinguish files, but that will give false signal on empty files.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is the only way to test for file status is to check if ‘/’ is at the end of the element?

>Solution :

According to documentation:

from zipfile import ZipFile, Path
archive = ZipFile('ZIP_PATH')
for name in archive.namelist():
    print(Path(root= archive, at= name).is_dir())
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading