Ich habe die zipfile
-Dokumentation durchgelesen, konnte aber nicht verstehen, wie eine Datei entpackt wird, sondern nur, wie eine Datei komprimiert wird. Wie entpacke ich den gesamten Inhalt einer Zip-Datei in dasselbe Verzeichnis?
import zipfile
with zipfile.ZipFile(path_to_Zip_file, 'r') as Zip_ref:
Zip_ref.extractall(directory_to_extract_to)
Das wars so ziemlich!
Wenn Sie Python 3.2 oder höher verwenden:
import zipfile
with zipfile.ZipFile("file.Zip","r") as Zip_ref:
Zip_ref.extractall("targetdir")
Sie müssen nicht das nahe oder versuchen/fangen mit diesem als es wird die Kontextmanager -Konstruktion verwendet.
Verwenden Sie die extractall
-Methode, wenn Sie Python 2.6+ verwenden
Zip = ZipFile('file.Zip')
Zip.extractall()
Sie können auch nur ZipFile
importieren:
from zipfile import ZipFile
zf = ZipFile('path_to_file/file.Zip', 'r')
zf.extractall('path_to_extract_folder')
zf.close()
Funktioniert in Python 2 und Python 3 .
python filename.py
für die RAR-Unterstützung müssen Sie die Pakete unrar und rarfile python installieren.
pip install unrar
pip install rarfile
Sie sind noch nicht fertig, jetzt müssen Sie auch das Unrar für Windows und Linux manuell installieren.
Für Linux:
Sudo apt-get install unrar
Für Windows :
Es installieren.
Normalerweise ist der Standort:
C:\Program Files (x86)\GnuWin32\bin\unrar.exe
Fügen Sie diesen Pfad in Ihre Windows-Pfadvariablen ein , da dieser Pfad der Pfad des Unrar-Tools ist, der zum Zeitpunkt des Extrahierens der RAR-Datei verwendet wird.
rarfile.UNRAR_TOOL = C:\Program Files (x86)\GnuWin32\bin\unrar.exe
Wenn alles eingerichtet ist, können Sie es bereitstellen.
#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)
Keine Panik, es ist ein langes Drehbuch, das hauptsächlich aus vier Teilen besteht.
Stellen Sie sicher, dass Sie die Pfadvariable korrekt installiert haben. Dieser Abschnitt ist nicht erforderlich, wenn Sie nicht mit der RAR-Datei arbeiten möchten.
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)
Diese Funktion extrahiert eine Zip-Datei. Nimmt zwei Argumente loc und outloc. loc = "Dateiname mit absolutem Pfad". outloc = "Datei, in die extrahiert werden soll".
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()
Diese Funktion extrahiert eine RAR-Datei. Fast gleich wie 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")
Die Hauptfunktion fragt den Benutzer nach dem absoluten Pfad. Sie können einen vordefinierten Pfad festlegen, indem Sie den Positionswert festlegen. und die Eingabefunktion auskommentieren.
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")
Ich habe mit der von WinRAR erstellten RAR nachgeprüft, dass sie eine Warnung enthält und die Dateien nicht extrahiert.
[Bitte kommentieren Sie, ob Sie in Bezug auf diese Warnung und Ausgabe helfen können.]
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
Aber es kann leicht RAR4-Typ extrahieren.
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)
Dies beinhaltet keine Validierung für die Datei, wenn diese nicht Zip ist. Wenn der Ordner keine ZIP-Datei enthält, schlägt dies fehl.
versuche dies :
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()
pfad: Entpacken Sie den Pfad der Datei