J'ai lu la zipfile
documentation , mais je ne comprenais pas comment décompresser un fichier, mais comment Zip un fichier. Comment décompresser tout le contenu d'un fichier Zip dans le même répertoire?
import zipfile
with zipfile.ZipFile(path_to_Zip_file, 'r') as Zip_ref:
Zip_ref.extractall(directory_to_extract_to)
C'est à peu près ça!
Si vous utilisez Python 3.2 ou une version ultérieure:
import zipfile
with zipfile.ZipFile("file.Zip","r") as Zip_ref:
Zip_ref.extractall("targetdir")
Vous n'avez pas besoin d'utiliser le close ou try/catch avec ceci il utilise la construction gestionnaire de contexte .
Utilisez la méthode extractall
, si vous utilisez Python 2.6+
Zip = ZipFile('file.Zip')
Zip.extractall()
Vous pouvez également importer uniquement ZipFile
:
from zipfile import ZipFile
zf = ZipFile('path_to_file/file.Zip', 'r')
zf.extractall('path_to_extract_folder')
zf.close()
Fonctionne en Python 2 et Python 3 .
python filename.py
pour la prise en charge RAR, vous devez installer les packages unrar et rarfile python.
pip install unrar
pip install rarfile
Vous n'avez pas encore terminé, vous devez également installer manuellement unrar pour Windows et Linux.
Pour Linux:
Sudo apt-get install unrar
Pour les fenêtres :
Installez-le.
Normalement, l'emplacement est:
C:\Program Files (x86)\GnuWin32\bin\unrar.exe
Ajoutez ce chemin dans vos variables de chemin Windows. car ce chemin sera le chemin de l'outil unrar qui sera utilisé lors de l'extraction du fichier RAR.
rarfile.UNRAR_TOOL = C:\Program Files (x86)\GnuWin32\bin\unrar.exe
Si tout est configuré, vous êtes prêt à déployer.
#import Zip file.
import zipfile
# import rarfile
import rarfile
# for path checking.
import os.path
# deleting directory.
import shutil
def check_archrive_file(loc):
'''
check the file is an archive file or not.
if the file is an archive file just extract it using the proper extracting method.
'''
# check if it is a Zip file or not.
if (loc.endswith('.Zip') or loc.endswith('.rar')):
# chcek the file is present or not .
if os.path.isfile(loc):
#create a directory at the same location where file will be extracted.
output_directory_location = loc.split('.')[0]
# if os path not exists .
if not os.path.exists(output_directory_location):
# create directory .
os.mkdir(output_directory_location)
print(" Otput Directory " , output_directory_location)
# extract
if loc.endswith('.Zip'):
extractzip(loc,output_directory_location)
else:
extractrar(loc,output_directory_location)
else:
# Directory allready exist.
print("Otput Directory " , output_directory_location)
# deleting previous directoty .
print("Deleting old Otput Directory ")
## Try to remove tree; if failed show an error using try...except on screen
try:
# delete the directory .
shutil.rmtree(output_directory_location)
# delete success
print("Delete success now extracting")
# extract
# extract
if loc.endswith('.Zip'):
extractzip(loc,output_directory_location)
else:
extractrar(loc,output_directory_location)
except OSError as e:
print ("Error: %s - %s." % (e.filename, e.strerror))
else:
print("File not located to this path")
else:
print("File do not have any archrive structure.")
def extractzip(loc,outloc):
'''
using the zipfile tool extract here .
This function is valid if the file type is Zip only
'''
with zipfile.ZipFile(loc,"r") as Zip_ref:
# iterate over Zip info list.
for item in Zip_ref.infolist():
Zip_ref.extract(item,outloc)
# once extraction is complete
# check the files contains any Zip file or not .
# if directory then go through the directoty.
Zip_files = [files for files in Zip_ref.filelist if files.filename.endswith('.Zip')]
# print other Zip files
# print(Zip_files)
# iterate over Zip files.
for file in Zip_files:
# iterate to get the name.
new_loc = os.path.join(outloc,file.filename)
#new location
# print(new_loc)
#start extarction.
check_archrive_file(new_loc)
# close.
Zip_ref.close()
def extractrar(loc,outloc):
'''
using the rarfile tool extract here .
this function is valid if the file type is rar only
'''
#check the file is rar or not
if(rarfile.is_rarfile(loc)):
with rarfile.RarFile(loc,"r") as rar_ref:
# iterate over Zip info list.
for item in rar_ref.infolist():
rar_ref.extract(item,outloc)
# once extraction is complete
# get the name of the rar files inside the rar.
rar_files = [file for file in rar_ref.infolist() if file.filename.endswith('.rar') ]
# iterate
for file in rar_files:
# iterate to get the name.
new_loc = os.path.join(outloc,file.filename)
#new location
# print(new_loc)
#start extarction.
check_archrive_file(new_loc)
# close.
rar_ref.close()
else:
print("File "+loc+" is not a rar file")
def checkpathVariables():
'''
check path variables.
if unrar.exe nor present then
install unrar and set unrar.exe in path variable.
'''
try:
user_paths = os.environ['PYTHONPATH'].split(os.pathsep)
except KeyError:
user_paths = []
# iterate over paths.
for item in user_paths:
print("User path python variables :"+user_paths)
# check rar tool exe present or not.
for item in user_paths:
# print(item)
if("unrar.exe" in item):
print("Unrar tool setup found PYTHONPATH")
return
print("Unrar tool setup not found in PYTHONPATH")
# print os path
os_paths_list = os.environ['PATH'].split(';')
# check rar tool exe present or not.
for item in os_paths_list:
# print(item)
if("unrar.exe" in item):
print("Unrar tool setup found in PATH")
rarfile.UNRAR_TOOL = item
print("Unrar tool path set up complete ."+item)
return
print("Unrar tool setup not found in PATH")
print("RAR TOOL WILL NOT WORK FOR YOU.")
downloadlocation = "https://www.rarlab.com/rar/unrarw32.exe"
print("install unrar form the link"+downloadlocation)
# run the main function
if __== '__main__':
'''
before you run this function make sure you have installed two packages
unrar and rarfile.
if not installed then
pip install unrar
pip install rarfile.
This is not only the case unrar tool should be set up.
Zip is included in standard library so do not worry about the Zip file.
'''
# check path and variables.
checkpathVariables()
# Take input form the user.
location = input('Please provide the absolute path of the Zip/rar file-----> ')
check_archrive_file(location)
Ne paniquez pas, il s’agit d’un long scénario divisé en quatre parties.
Vérifiez que vous avez correctement installé la variable the path. Cette section n'est pas obligatoire si vous ne souhaitez pas utiliser de fichier RAR.
def checkpathVariables():
'''
check path variables.
if unrar.exe nor present then
install unrar and set unrar.exe in path variable.
'''
try:
user_paths = os.environ['PYTHONPATH'].split(os.pathsep)
except KeyError:
user_paths = []
# iterate over paths.
for item in user_paths:
print("User path python variables :"+user_paths)
# check rar tool exe present or not.
for item in user_paths:
# print(item)
if("unrar.exe" in item):
print("Unrar tool setup found PYTHONPATH")
return
print("Unrar tool setup not found in PYTHONPATH")
# print os path
os_paths_list = os.environ['PATH'].split(';')
# check rar tool exe present or not.
for item in os_paths_list:
# print(item)
if("unrar.exe" in item):
print("Unrar tool setup found in PATH")
rarfile.UNRAR_TOOL = item
print("Unrar tool path set up complete ."+item)
return
print("Unrar tool setup not found in PATH")
print("RAR TOOL WILL NOT WORK FOR YOU.")
downloadlocation = "https://www.rarlab.com/rar/unrarw32.exe"
print("install unrar form the link"+downloadlocation)
Cette fonction extrait un fichier Zip. Prend deux arguments loc et outloc. loc = "Nom du fichier avec chemin absolu". outloc = "Fichier où il sera extrait".
def extractzip(loc,outloc):
'''
using the zipfile tool extract here .
This function is valid if the file type is Zip only
'''
with zipfile.ZipFile(loc,"r") as Zip_ref:
# iterate over Zip info list.
for item in Zip_ref.infolist():
Zip_ref.extract(item,outloc)
# once extraction is complete
# check the files contains any Zip file or not .
# if directory then go through the directoty.
Zip_files = [files for files in Zip_ref.filelist if files.filename.endswith('.Zip')]
# print other Zip files
# print(Zip_files)
# iterate over Zip files.
for file in Zip_files:
# iterate to get the name.
new_loc = os.path.join(outloc,file.filename)
#new location
# print(new_loc)
#start extarction.
check_archrive_file(new_loc)
# close.
Zip_ref.close()
Cette fonction extrait un fichier RAR. Presque pareil que Zip.
def extractrar(loc,outloc):
'''
using the rarfile tool extract here .
this function is valid if the file type is rar only
'''
#check the file is rar or not
if(rarfile.is_rarfile(loc)):
with rarfile.RarFile(loc,"r") as rar_ref:
# iterate over Zip info list.
for item in rar_ref.infolist():
rar_ref.extract(item,outloc)
# once extraction is complete
# get the name of the rar files inside the rar.
rar_files = [file for file in rar_ref.infolist() if file.filename.endswith('.rar') ]
# iterate
for file in rar_files:
# iterate to get the name.
new_loc = os.path.join(outloc,file.filename)
#new location
# print(new_loc)
#start extarction.
check_archrive_file(new_loc)
# close.
rar_ref.close()
else:
print("File "+loc+" is not a rar file")
La fonction principale demande à l'utilisateur le chemin absolu. Vous pouvez le changer en un chemin prédéfini en définissant la valeur d'emplacement. et commentez la fonction d'entrée.
if __== '__main__':
'''
before you run this function make sure you have installed two packages
unrar and rarfile.
if not installed then
pip install unrar
pip install rarfile.
This is not only the case unrar tool should be set up.
Zip is included in standard library so do not worry about the Zip file.
'''
# check path and variables.
checkpathVariables()
# Take input form the user.
location = input('Please provide the absolute path of the Zip/rar file-----> ')
check_archrive_file(location)
rarfile.is_rarfile("filename")
J'ai vérifié avec le RAR créé par WinRAR, il fournit un avertissement et n'extrait pas les fichiers.
[Veuillez commenter si vous pouvez aider à propos de cet avertissement et isuue]
rarfile.RarWarning: Non-fatal error [1]: b'\r\nD:\\Kiosk\\Download\\Tutorial\\reezoo\\a.rar is not RAR archive\r\nNo files to extract\r\n
Mais il peut facilement extraire le type RAR4.
import os
Zip_file_path = "C:\AA\BB"
file_list = os.listdir(path)
abs_path = []
for a in file_list:
x = Zip_file_path+'\\'+a
print x
abs_path.append(x)
for f in abs_path:
Zip=zipfile.ZipFile(f)
Zip.extractall(Zip_file_path)
Cela ne contient pas de validation pour le fichier s'il ne s'agit pas de Zip. Si le dossier contient un fichier autre que .Zip, il échouera.
essaye ça :
import zipfile
def un_zipFiles(path):
files=os.listdir(path)
for file in files:
if file.endswith('.Zip'):
filePath=path+'/'+file
Zip_file = zipfile.ZipFile(filePath)
for names in Zip_file.namelist():
Zip_file.extract(names,path)
Zip_file.close()
chemin: le chemin du fichier de décompression