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.
Is the only way to test for file status is to check if '/' is at the end of the element?
CodePudding user response:
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())