logo

Treballant amb fitxers zip a Python

Aquest article explica com es poden realitzar diverses operacions en un fitxer zip mitjançant un programa Python senzill. Què és un fitxer zip? ZIP és un format d'arxiu que admet la compressió de dades sense pèrdua. Per compressió sense pèrdues volem dir que l'algoritme de compressió permet reconstruir perfectament les dades originals a partir de les dades comprimides. Per tant, un fitxer ZIP és un únic fitxer que conté un o més fitxers comprimits que ofereix una manera ideal de fer que els fitxers grans siguin més petits i mantenir els fitxers relacionats junts. Per què necessitem fitxers zip?
  • Per reduir els requisits d'emmagatzematge.
  • Per millorar la velocitat de transferència sobre les connexions estàndard.
Per treballar amb fitxers zip amb Python, utilitzarem un mòdul Python integrat anomenat fitxer zip .

1. Extracció d'un fitxer zip

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: Treballant amb fitxers zip a Python' title=Intentem entendre el codi anterior a trossos:
  • 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 LLEGIR mode i anomena-lo com cremallera .
  • zip.printdir()
    printdir() El mètode imprimeix una taula de continguts per a l'arxiu.
  • zip.extractall()
    extractall() El mètode extreu tot el contingut del fitxer zip al directori de treball actual. També pots trucar extracte () 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. Escriptura en un fitxer zip

Considereu un directori (carpeta) amb aquest format: Treballant amb fitxers zip a Python' title= 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: Treballant amb fitxers zip a Python' title=Intentem entendre el codi anterior dividint-lo en fragments:
  • 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()  mètode. En cada iteració, tots els fitxers presents en aquest directori s'afegeixen a una llista anomenada camins_fitxers . Al final tornem tots els camins dels fitxers.
  • file_paths = get_all_file_paths(directory)
    Here we pass the directory to be zipped to the get_all_file_paths() funció i obteniu una llista que conté tots els camins dels fitxers.
  • 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 escriure mètode.

3. Obtenir tota la informació sobre un fitxer zip



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('tModified:t' + str(datetime.datetime(*info.date_time))) print('tSystem:tt' + str(info.create_system) + '(0 = Windows 3 = Unix)') print('tZIP version:t' + str(info.create_version)) print('tCompressed:t' + str(info.compress_size) + ' bytes') print('tUncompressed:t' + str(info.file_size) + ' bytes') 
The output of above program may look like this: ' title=
for info in zip.infolist():
Here llista d'informació () mètode crea una instància de ZipInfo classe que conté tota la informació sobre el fitxer zip. Podem accedir a tota la informació, com ara la data de l'última modificació dels fitxers, el sistema de noms de fitxers en què s'han creat els fitxers Mida de la versió Zip dels fitxers en forma comprimida i no comprimida, etc. Nikhil Kumar . Crea un qüestionari