我正在尝试创建一个应该解压缩一堆文件的脚本。对于其中一些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)
感谢您的建议......
答案 0 :(得分:0)
您正在尝试创建一个与您要解压缩的档案名称相同的文件夹:
os.mkdir(ArchivesZip)
你可能想要:
os.makedirs(dir)
现在应该将每个.zip文件解压缩到"提取/路径/到/ archive.zip'工作目录内的文件夹。
如果要更改文件的提取位置,只需相应地修改dir
变量即可
我不确定您想要什么,但os.path.basename()和os.path.splitext()可能会有用。
另请注意,dir
会隐藏内置的dir()
,因此它是一个错误的变量名称。
答案 1 :(得分:0)
感谢Stranac。
此代码现在有效!
然而,有些事情困扰着我。 首先,我需要为目录变量使用全局变量,可以在Extract Button中重复使用。我不确定(当我开始学习Python时)只是将目录声明为全局变量是个不错的选择。
欢迎任何改进代码的建议:)
# -*- 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()