即使zip文件没有文件夹,也可以递归解压缩

2024-04-20 01:02:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我在试着做一个脚本,可以解压一堆文件。对于其中一些zip文件,没有由文件夹构成的结构。这意味着所有文件都放在同一级别的归档文件中,当我试图解压它们时,zip文件中包含的所有文件都在同一级别解压。因此,所有文件都混合在一起,而不是单独放在相应的档案中。你知道吗

我的想法是从相应的zip归档文件中创建一个名为的新文件夹,并对工作目录中包含的所有zip文件执行此操作。 但是,如果我使用makedirs(),就不会得到它。你知道吗

这是我的密码:

os.chdir(directory)
cwd = os.getcwd()
print("Working directory :",cwd)

for ArchivesZip in glob.glob(os.path.join(directory,'*.zip')):
    zip_ref = zipfile.ZipFile(ArchivesZip,'r')
    dir = os.path.join("extractions",ArchivesZip)
    if not os.path.exists(dir):
        os.mkdir(ArchivesZip)
        zip_ref.extractall(dir)

谢谢你的建议。。。你知道吗


Tags: 文件path脚本文件夹refosdirzip
2条回答

多亏了你斯特拉克。你知道吗

这个代码现在起作用了!你知道吗

只是有些事困扰着我。 首先,我需要为目录变量使用一个全局变量,可在Extract按钮中重用。我不确定(当我开始学习Python时)仅仅将directory声明为全局变量是一个好的选择。你知道吗

欢迎提出任何改进代码的建议:)

   # -*- coding: iso-8859-1 -*-
from Tkinter import *
import zipfile,os,tkFileDialog,Tkinter,glob
#déclaration variables fenêtre Tkinter
master = Tk()
master.minsize(800,100)

#création fonction pour bouton d'appel
def callback():
#Ouverture navigateur, choix du dossier qui contient les zips
    global directory
    directory = tkFileDialog.askdirectory(parent=master,initialdir="/Users/me/Downloads/",title='Please select a directory')
    if len(directory) > 0 :
        os.chdir(directory)
        cwd = os.getcwd()
        ExtractButton['state'] = 'active'


#ICI ça marche

def extraction():
#Ne cherche que les fichiers de type *.zip        
    for ArchivesZip in glob.glob(os.path.join(directory,'*.zip')):    
        truncated_file = os.path.splitext(os.path.basename(ArchivesZip))[0]
        print(truncated_file)
        if not os.path.exists(truncated_file):
            os.makedirs(truncated_file)
            zip_ref = zipfile.ZipFile(ArchivesZip,'r')
            zip_ref.extractall(truncated_file)
    ExtractButton['state'] = 'disabled'


#Appel des fonctions pour chacun des boutons. Parcourir et Extraire
SelectButton = Button(master, text="Parcourir", command=callback)
ExtractButton = Button(master, text="Extraction", state=DISABLED, command=extraction)

SelectButton.pack()
ExtractButton.pack()

mainloop()

您正在尝试创建一个与要解包的存档名相同的文件夹:

os.mkdir(ArchivesZip)

你可能想要:

os.makedirs(dir)

每个.zip文件现在都应该被提取到'extractions/path/to'中/存档.zip'工作目录中的文件夹。
如果要更改提取文件的位置,只需相应地修改dir变量即可。
我不确定你到底想要什么,但是os.path.basename()os.path.splitext()可能有用。你知道吗

另外,请注意,dir隐藏了内置的dir(),因此它是一个错误的变量名。你知道吗

相关问题 更多 >