Python で zip ファイルを操作する

Python で zip ファイルを操作する
この記事では、簡単な Python プログラムを使用して zip ファイルに対してさまざまな操作を実行する方法を説明します。 zipファイルとは何ですか? ZIP は、可逆データ圧縮をサポートするアーカイブ ファイル形式です。可逆圧縮とは、圧縮アルゴリズムによって圧縮データから元のデータを完全に再構築できることを意味します。したがって、ZIP ファイルは 1 つまたは複数の圧縮ファイルを含む単一のファイルであり、大きなファイルを小さくし、関連ファイルをまとめて保持するための理想的な方法を提供します。 なぜ zip ファイルが必要なのでしょうか?
  • ストレージ要件を軽減するため。
  • 標準接続での転送速度を向上させるため。
Python を使用して zip ファイルを操作するには、という組み込みの 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: Python で zip ファイルを操作する上記のコードを部分的に理解してみましょう。
  • 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() 
    プリントディレクトリ() メソッドは、アーカイブの目次を出力します。
  • 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 ファイルへの書き込み

次のような形式のディレクトリ (フォルダー) を考えてみましょう。 Python で zip ファイルを操作する 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: Python で zip ファイルを操作する上記のコードをいくつかの断片に分けて理解してみましょう。
  • 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 情報リスト() メソッドはインスタンスを作成します ジップインフォ zip ファイルに関するすべての情報が含まれるクラス。ファイルの最終変更日、ファイルが作成されたファイル名システム、圧縮形式および非圧縮形式のファイルの ZIP バージョン サイズなど、すべての情報にアクセスできます。この記事は次の寄稿者によるものです。 ニキル・クマール クイズの作成