Flora
Flora

Reputation: 285

Get name of folders in zip files - Python

I have been searching the whole stackoverflow to get an idea on how to extract only names of subfolders from a zip file path.

I tried using tkinter to get the zip path:

Import os
from tkinter import filedialog
import tkinter as tk
from zipfile import ZipFile

root = tk.Tk()
root.withdraw()
root.filename = filedialog.askopenfilename(initialdir=os.getcwd(), title="Select file", filetypes=[("zip", "*.zip")])

And used the ZipFile and namelist to hopefully get the names of all subfolders.

with ZipFile(root.filename, 'r') as f:
    names = f.namelist()

However, I get that:

['CS10/', 'CS10/.DS_Store', '__MACOSX/', '__MACOSX/CS10/', '__MACOSX/CS10/._.DS_Store', etc........

I want to know if there is a way to just get the folder name which is in this case CS10 and so on.

Example: If I have 3 folders named: "Apple" "Orange" "Pear" in a zip file path(Users/Kiona/fruits.zip), I want to print ['Apple','Orange','Pear'].

Upvotes: 9

Views: 7438

Answers (1)

joslarson
joslarson

Reputation: 1694

I haven't tested this, but the following might be what you're looking for:

with ZipFile(root.filename, 'r') as f:
    names = [info.filename for info in f.infolist() if info.is_dir()]

For reference, look at https://docs.python.org/3.6/library/zipfile.html#zipfile.ZipFile.infolist and https://docs.python.org/3.6/library/zipfile.html#zipfile.ZipInfo.is_dir

Upvotes: 9

Related Questions