Arbeiten mit ZIP-Dateien in Python

Arbeiten mit ZIP-Dateien in Python
In diesem Artikel wird erklärt, wie man mit einem einfachen Python-Programm verschiedene Vorgänge an einer ZIP-Datei ausführen kann. Was ist eine Zip-Datei? ZIP ist ein Archivdateiformat, das verlustfreie Datenkomprimierung unterstützt. Unter verlustfreier Komprimierung verstehen wir, dass der Komprimierungsalgorithmus eine perfekte Rekonstruktion der Originaldaten aus den komprimierten Daten ermöglicht. Eine ZIP-Datei ist also eine einzelne Datei, die eine oder mehrere komprimierte Dateien enthält und bietet eine ideale Möglichkeit, große Dateien zu verkleinern und zusammengehörige Dateien zusammenzuhalten. Warum brauchen wir ZIP-Dateien?
  • Um den Speicherbedarf zu reduzieren.
  • Zur Verbesserung der Übertragungsgeschwindigkeit gegenüber Standardverbindungen.
Um mit Python an ZIP-Dateien zu arbeiten, verwenden wir ein integriertes Python-Modul namens zip-Datei .

1. Extrahieren einer ZIP-Datei

Python
   # importing required modules   from   zipfile   import   ZipFile   # specifying the zip file name   file_name   =   'my_python_files.zip'   # opening the zip file in READ mode   with   ZipFile  (  file_name     'r'  )   as   zip  :   # printing all the contents of the zip file   zip  .  printdir  ()   # extracting all the files   print  (  'Extracting all the files now...'  )   zip  .  extractall  ()   print  (  'Done!'  )   
The above program extracts a zip file named 'my_python_files.zip' in the same directory as of this python script. The output of above program may look like this: Arbeiten mit ZIP-Dateien in PythonVersuchen wir, den obigen Code in Teilen zu verstehen:
  • from zipfile import ZipFile 
    ZipFile is a class of zipfile module for reading and writing zip files. Here we import only class ZipFile from zipfile module.
  • with ZipFile(file_name 'r') as zip: 
    Here a ZipFile object is made by calling ZipFile constructor which accepts zip file name and mode parameters. We create a ZipFile object in LESEN Modus und benennen Sie ihn als Reißverschluss .
  • zip.printdir() 
    printdir() Die Methode gibt ein Inhaltsverzeichnis für das Archiv aus.
  • zip.extractall() 
    extractall() Die Methode extrahiert den gesamten Inhalt der ZIP-Datei in das aktuelle Arbeitsverzeichnis. Sie können auch anrufen Extrakt() method to extract any file by specifying its path in the zip file. For example:
    zip.extract('python_files/python_wiki.txt') 
    This will extract only the specified file. If you want to read some specific file you can go like this:
    data = zip.read(name_of_file_to_read) 

2. Schreiben in eine ZIP-Datei

Betrachten Sie ein Verzeichnis (Ordner) mit einem solchen Format: Arbeiten mit ZIP-Dateien in Python Here we will need to crawl the whole directory and its sub-directories in order to get a list of all file paths before writing them to a zip file. The following program does this by crawling the directory to be zipped: Python
   # importing required modules   from   zipfile   import   ZipFile   import   os   def   get_all_file_paths  (  directory  ):   # initializing empty file paths list   file_paths   =   []   # crawling through directory and subdirectories   for   root     directories     files   in   os  .  walk  (  directory  ):   for   filename   in   files  :   # join the two strings in order to form the full filepath.   filepath   =   os  .  path  .  join  (  root     filename  )   file_paths  .  append  (  filepath  )   # returning all file paths   return   file_paths   def   main  ():   # path to folder which needs to be zipped   directory   =   './python_files'   # calling function to get all file paths in the directory   file_paths   =   get_all_file_paths  (  directory  )   # printing the list of all files to be zipped   print  (  'Following files will be zipped:'  )   for   file_name   in   file_paths  :   print  (  file_name  )   # writing files to a zipfile   with   ZipFile  (  'my_python_files.zip'    'w'  )   as   zip  :   # writing each file one by one   for   file   in   file_paths  :   zip  .  write  (  file  )   print  (  'All files zipped successfully!'  )   if   __name__   ==   '__main__'  :   main  ()   
The output of above program looks like this: Arbeiten mit ZIP-Dateien in PythonVersuchen wir, den obigen Code zu verstehen, indem wir ihn in Fragmente unterteilen:
  • def get_all_file_paths(directory): file_paths = [] for root directories files in os.walk(directory): for filename in files: filepath = os.path.join(root filename) file_paths.append(filepath) return file_paths 
    First of all to get all file paths in our directory we have created this function which uses the os.walk()  Verfahren. In jeder Iteration werden alle in diesem Verzeichnis vorhandenen Dateien an eine Liste mit dem Namen angehängt Dateipfade . Am Ende geben wir alle Dateipfade zurück.
  • file_paths = get_all_file_paths(directory) 
    Here we pass the directory to be zipped to the get_all_file_paths() Funktion und erhalten Sie eine Liste mit allen Dateipfaden.
  • with ZipFile('my_python_files.zip''w') as zip: 
    Here we create a ZipFile object in WRITE mode this time.
  • for file in file_paths: zip.write(file) 
    Here we write all the files to the zip file one by one using schreiben Verfahren.

3. Alle Informationen zu einer ZIP-Datei abrufen

Python
   # importing required modules   from   zipfile   import   ZipFile   import   datetime   # specifying the zip file name   file_name   =   'example.zip'   # opening the zip file in READ mode   with   ZipFile  (  file_name     'r'  )   as   zip  :   for   info   in   zip  .  infolist  ():   print  (  info  .  filename  )   print  (  '  t  Modified:  t  '   +   str  (  datetime  .  datetime  (  *  info  .  date_time  )))   print  (  '  t  System:  tt  '   +   str  (  info  .  create_system  )   +   '(0 = Windows 3 = Unix)'  )   print  (  '  t  ZIP version:  t  '   +   str  (  info  .  create_version  ))   print  (  '  t  Compressed:  t  '   +   str  (  info  .  compress_size  )   +   ' bytes'  )   print  (  '  t  Uncompressed:  t  '   +   str  (  info  .  file_size  )   +   ' bytes'  )   
The output of above program may look like this:
for info in zip.infolist(): 
Here infolist() Methode erstellt eine Instanz von ZipInfo Klasse, die alle Informationen über die ZIP-Datei enthält. Wir können auf alle Informationen zugreifen, z. B. das Datum der letzten Änderung der Dateien, die Dateinamen, das System, auf dem die Dateien erstellt wurden, die Zip-Version, die Größe der Dateien in komprimierter und unkomprimierter Form usw. Dieser Artikel wurde von verfasst Nikhil Kumar . Quiz erstellen