Badiou30120 Badiou30120 - 24 days ago 9
Python Question

Python : Zip extraction exception

I made an automatic extractor for my music catalog.
I wrote my code as sort to work with zips and rar files.
The code is working fine but if there are other kind of files in the working directories, then I receive an error message :

raise BadZipfile, "File is not a zip file"
BadZipfile: File is not a zip file


That means a mp3 file or anything else is blocking or interrupting the extraction process.
Here's my code :

def extraction():
funcs = {'.rar':rarfile.RarFile, '.zip':zipfile.ZipFile}
for ArchivesFiles in chemin_zipfiles :
truncated_file, ext = os.path.splitext(os.path.basename(ArchivesFiles))
if not os.path.exists(truncated_file):
new_folder = os.makedirs(truncated_file)
arch_ref = funcs[ext](ArchivesFiles,'r')
new_folder = os.path.realpath(truncated_file)
arch_ref.extractall(new_folder)


How could I avoid this?

edit :

I made some changes:

def extraction():
funcs = {'.rar':rarfile.RarFile, '.zip':zipfile.ZipFile}
for ArchivesFiles in chemin_zipfiles :
truncated_file, ext = os.path.splitext(os.path.basename(ArchivesFiles))
if not os.path.exists(truncated_file):
new_folder = os.makedirs(truncated_file)
arch_ref = funcs[ext](ArchivesFiles,'r')
new_folder = os.path.realpath(truncated_file)
try:
arch_ref.extractall(new_folder)
except BadZipfile:
continue
except NotRarFile:
continue


but still receiving an error:

raise NotRarFile("Not a Rar archive: "+self.rarfile)
NotRarFile: Not a Rar archive: /Volumes/me/albums/reggae/reggae_dub/._Dubalizer_SubExisteÌncia_freshpoulp.rar


Many thanks.

Answer

I think there are two ways. First you could catch the exception:

try:
    arch_ref.extractall(new_folder)
except BadZipfile:
    continue

or you could try to prevent loading non-zip files by filtering the file extension and/or checking the file header.

Comments