Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 !

like image 986
Flora Avatar asked Oct 25 '17 23:10

Flora


People also ask

How do I get a list of filenames in a directory in Python?

To get a list of all the files and folders in a particular directory in the filesystem, use os. listdir() in legacy versions of Python or os. scandir() in Python 3.


1 Answers

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

like image 56
joslarson Avatar answered Sep 28 '22 19:09

joslarson