Работа с zip файлове в Python

Работа с zip файлове в Python
Тази статия обяснява как човек може да извършва различни операции върху zip файл с помощта на проста програма на Python. Какво е zip файл? ZIP е формат на архивен файл, който поддържа компресиране на данни без загуба. Под компресия без загуби имаме предвид, че алгоритъмът за компресиране позволява оригиналните данни да бъдат идеално реконструирани от компресираните данни. Така че ZIP файлът е един файл, съдържащ един или повече компресирани файлове, предлагащ идеален начин да направите големите файлове по-малки и да запазите свързаните файлове заедно. Защо се нуждаем от zip файлове?
  • За намаляване на изискванията за съхранение.
  • За подобряване на скоростта на трансфер през стандартни връзки.
За да работим върху zip файлове с помощта на python, ще използваме вграден модул на python, наречен zipфайл .

1. Извличане на 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: Работа с zip файлове в PythonНека се опитаме да разберем горния код на части:
  • 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 ПРОЧЕТЕТЕ режим и го наименувайте като цип .
  • zip.printdir() 
    printdir() метод отпечатва съдържанието на архива.
  • zip.extractall() 
    извличане() ще извлече цялото съдържание на zip файла в текущата работна директория. Можете също да се обадите екстракт() 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. Записване в zip файл

Помислете за директория (папка) с такъв формат: Работа с zip файлове в 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: Работа с zip файлове в PythonНека се опитаме да разберем горния код, като разделим на фрагменти:
  • 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()  метод. Във всяка итерация всички налични файлове в тази директория се добавят към списък, наречен файлови_пътища . Накрая връщаме всички пътеки към файловете.
  • file_paths = get_all_file_paths(directory) 
    Here we pass the directory to be zipped to the get_all_file_paths() функция и да получите списък, съдържащ всички файлови пътища.
  • 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 пишете метод.

3. Получаване на цялата информация за 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  (  '  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 инфолист() метод създава екземпляр на ZipInfo клас, който съдържа цялата информация за zip файла. Имаме достъп до цялата информация, като дата на последна модификация на файлове, система за имена на файлове, на която са създадени файловете, размер на Zip версията на файловете в компресиран и некомпресиран вид и т.н. Тази статия е предоставена от Никхил Кумар . Създаване на тест