简体   繁体   English

获取zip文件中的文件夹名称 - Python

[英]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. 我一直在搜索整个stackoverflow,以了解如何从zip文件路径中仅提取子文件夹的名称。

I tried using tkinter to get the zip path: 我尝试使用tkinter获取zip路径:

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. 并使用ZipFile和namelist来获取所有子文件夹的名称。

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. 我想知道是否有办法获取文件夹名称,在这种情况下CS10等等。

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'] 示例:如果我在zip文件路径中有3个名为“Apple”“Orange”“Pear”的文件夹(Users / Kiona / fruits.zip)我想打印['Apple','Orange','Pear']

I am pretty new with Python so I hope this doesn't sound like a very stupid problem. 我是Python的新手,所以我希望这听起来不是一个非常愚蠢的问题。

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 供参考,请参阅https://docs.python.org/3.6/library/zipfile.html#zipfile.ZipFile.infolisthttps://docs.python.org/3.6/library/zipfile.html#zipfile.ZipInfo .is_dir

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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