简体   繁体   中英

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']

I am pretty new with Python so I hope this doesn't sound like a very stupid problem.

Cheers !

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM