Python Forum
Using zipfile module - finding folders not files
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Using zipfile module - finding folders not files
#1
I would like to look into a zipped file and make sure it does not contain a Folder and only contains files. I am using Ubuntu 22 if that matters.
Is there just a way to list all folders or 'directories' in a zip file?

Currently I just determine if there is a '/' in the strings generated from the code below - which would indicate to me that the zipped files are in a "folder" and not just a bunch of files. Is there a better way?

(or is this related to 'everything is a file' in Linux? )

 b= ZipFile (FULL_PATH)
        for name in b.namelist():
        print (type(name),name)
        d=name.split('/')
        print (len(d), d[0])
Thanks.
Reply
#2
The ZipInfo class has a method is_dir() which should enable you to tell whether members of the archive are directories.
« We can solve any problem by introducing an extra level of indirection »
Reply
#3
There is a function .is_dir() Look here.

Quite how that works I don't know, probably just does what you are doing!

from zipfile import ZipFile

path2zip = '/home/pedro/tmp/testme.zip'

with ZipFile(path2zip) as archive:
    folders = []
    for file in archive.namelist():
        file_info = archive.getinfo(file)
        if file_info.is_dir():
            info = archive.getinfo(file)
            folder_name = info.filename.rstrip("/")
            folders.append(folder_name)
            print(f'This zip file contains a folder: {info.filename.rstrip("/")}')
    print(f'the folders in this zip file are {folders}')
Gribouillis likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  zipfile module error pseudo 3 855 Jun-30-2023, 03:52 PM
Last Post: Gribouillis
  Create new folders and copy files cocobolli 3 1,566 Mar-22-2023, 10:23 AM
Last Post: Gribouillis
  Copy only hidden files and folders with rsync Cannondale 2 1,081 Mar-04-2023, 02:48 PM
Last Post: Cannondale
  Merge htm files with shutil library (TypeError: 'module' object is not callable) Melcu54 5 1,707 Aug-28-2022, 07:11 AM
Last Post: Melcu54
  [Solved by deanhystad] Create a zip file using zipfile library DZ_Galaxy 2 1,238 Aug-17-2022, 04:57 PM
Last Post: DZ_Galaxy
  Can ZipFile be used to extract hidden files? AiedailEclipsed 0 1,676 Mar-22-2022, 05:21 PM
Last Post: AiedailEclipsed
  Finding files matching pattern GrahamL 1 1,339 Jan-14-2022, 01:16 PM
Last Post: DeaD_EyE
  Created zipfile without all the subfolder? korenron 3 3,899 Jun-23-2021, 12:44 PM
Last Post: korenron
  Create ZIP file not working using ZipFile? korenron 1 2,162 Jun-13-2021, 04:15 PM
Last Post: korenron
  Moving files to Folders giddyhead 13 9,341 Mar-07-2021, 02:50 AM
Last Post: giddyhead

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020