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 !
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With