Python
 Computer >> コンピューター >  >> プログラミング >> Python

PythonのzipfileモジュールでファイルをZIP圧縮する方法【サンプルコード付き】

課題

Pythonを使ってファイルを圧縮(ZIP化)したい場合があります。

はじめに

ZIPファイルは、複数のファイルの内容をひとつにまとめて圧縮して格納できるアーカイブ形式です。ファイルを圧縮するとディスク上のサイズが小さくなるため、インターネット経由での送受信や、Control-M AFT・Connect:Direct・scpなどを利用したシステム間のファイル転送において非常に便利です。

Pythonでは、標準ライブラリのzipfileモジュールに含まれる関数を使うことで、簡単にZIPファイルを作成できます。

手順

1. 必要なパッケージの準備

本記事では zipfileio の2つのパッケージを使用します。どちらもPythonの標準ライブラリに含まれていますが、もし環境に存在しない場合は pip でインストールしてください。インストール済みかどうか不明な場合は、次のコマンドで確認できます。

pip freeze

2. データをファイルに書き込む関数を作成

まず、渡されたデータをCSVファイルとして書き出す関数 write_data_to_files を作成します。この関数はデータとファイル名を引数に受け取り、カレントディレクトリにファイルを生成します。

# Function : write_data_to_files
def write_data_to_files(inp_data, file_name):
    """
    function : create a csv file with the data passed to this code
    args : inp_data : data to be written to the target file
           file_name : target file name to store the data
    return : none
    assumption : File to be created and this code are in same directory.
    """
    print(f" *** Writing the data to - {file_name}")
    throwaway_storage = io.StringIO(inp_data)
    with open(file_name, 'w') as f:
        for line in throwaway_storage:
            f.write(line)

3. ファイルをZIP圧縮する関数を作成

次に、前のステップで作成したファイル群をZIPファイルに圧縮する関数 file_compress を作成します。この関数はファイル名のリストを受け取り、それぞれを順番に処理して1つのZIPファイルへ格納します。各ステップの詳細はコメントに記載しています。

独自の圧縮ZIPファイルを作成するには、ZipFileオブジェクトを書き込みモード('w')で開く必要があります。

ZipFileオブジェクトの write() メソッドにファイルのパスを渡すと、Pythonはそのパスにあるファイルを圧縮し、ZIPファイルに追加します。

  • write() の第1引数: 追加するファイル名の文字列
  • write() の第2引数: 圧縮方式のパラメータ。コンピュータに対して、どの圧縮アルゴリズムを使用するかを指定します
# Function : file_compress
def file_compress(inp_file_names, out_zip_file):
    """
    function : file_compress
    args : inp_file_names : list of filenames to be zipped
           out_zip_file : output zip file
    return : none
    assumption : Input file paths and this code is in same directory.
    """
    # 圧縮する場合は ZIP_DEFLATED を選択
    # 単に格納するだけなら zipfile.ZIP_STORED を使用
    compression = zipfile.ZIP_DEFLATED
    print(f" *** Input File name passed for zipping - {inp_file_names}")

    # ZIPファイルを作成(第1引数: パス/ファイル名、第2引数: モード)
    print(f' *** out_zip_file is - {out_zip_file}')
    zf = zipfile.ZipFile(out_zip_file, mode="w")

    try:
        for file_to_write in inp_file_names:
            # ファイルをZIPに追加
            # 第1引数: 圧縮対象ファイル、第2引数: ZIP内でのファイル名
            print(f' *** Processing file {file_to_write}')
            zf.write(file_to_write, file_to_write, compress_type=compression)

    except FileNotFoundError as e:
        print(f' *** Exception occurred during zip process - {e}')
    finally:
        # ファイルを閉じることを忘れずに!
        zf.close()

4. 関数を実行してCSVファイルを作成・圧縮する

作成した2つの関数を呼び出し、2つのCSVファイルを生成してからZIPファイルにまとめます。ここでは、グランドスラムで2回以上優勝したテニス選手のデータを temporary_file1_for_zip.csv に、1回以下しか優勝していない選手のデータを temporary_file2_for_zip.csv に書き込みます。その後、両方のファイルを temporary.zip という1つのZIPファイルに圧縮します。

import zipfile
import io
import pandas as pd

file_name1 = "temporary_file1_for_zip.csv"
file_name2 = "temporary_file2_for_zip.csv"
file_name_list = [file_name1, file_name2]
zip_file_name = "temporary.zip"

# ファイル1用のデータ
file_data_1 = """
player,titles
Federer,20
Nadal,20
Djokovic,17
Murray,3
"""

# ファイル2用のデータ
file_data_2 = """
player,titles
Thiem,1
Zverev,0
Medvedev,0
Rublev,0
"""

# データをファイルに書き込む
write_data_to_files(file_data_1, file_name1)
write_data_to_files(file_data_2, file_name2)

# ファイルをZIPファイルに圧縮する
file_compress(file_name_list, zip_file_name)

5. コード全体をまとめる

ここまで説明したすべてのステップを1つのスクリプトにまとめると、次のようになります。

import zipfile
import io
import pandas as pd

# Function : write_data_to_files
def write_data_to_files(inp_data, file_name):
    """
    function : create a csv file with the data passed to this code
    args : inp_data : data to be written to the target file
           file_name : target file name to store the data
    return : none
    assumption : File to be created and this code are in same directory.
    """
    print(f" *** Writing the data to - {file_name}")
    throwaway_storage = io.StringIO(inp_data)
    with open(file_name, 'w') as f:
        for line in throwaway_storage:
            f.write(line)

# Function : file_compress
def file_compress(inp_file_names, out_zip_file):
    """
    function : file_compress
    args : inp_file_names : list of filenames to be zipped
           out_zip_file : output zip file
    return : none
    assumption : Input file paths and this code is in same directory.
    """
    compression = zipfile.ZIP_DEFLATED
    print(f" *** Input File name passed for zipping - {inp_file_names}")

    print(f' *** out_zip_file is - {out_zip_file}')
    zf = zipfile.ZipFile(out_zip_file, mode="w")

    try:
        for file_to_write in inp_file_names:
            print(f' *** Processing file {file_to_write}')
            zf.write(file_to_write, file_to_write, compress_type=compression)

    except FileNotFoundError as e:
        print(f' *** Exception occurred during zip process - {e}')
    finally:
        zf.close()

# メインプログラム
if __name__ == '__main__':
    file_name1 = "temporary_file1_for_zip.csv"
    file_name2 = "temporary_file2_for_zip.csv"

    file_name_list = [file_name1, file_name2]
    zip_file_name = "temporary.zip"

    file_data_1 = """
player,titles
Federer,20
Nadal,20
Djokovic,17
Murray,3
"""

    file_data_2 = """
player,titles
Thiem,1
Zverev,0
Medvedev,0
Rublev,0
"""

    # データをファイルに書き込む
    write_data_to_files(file_data_1, file_name1)
    write_data_to_files(file_data_2, file_name2)

    # ファイルをZIPファイルに圧縮する
    file_compress(file_name_list, zip_file_name)

上記のコードを実行すると、コンソールには次のようなログが出力されます。

*** Writing the data to - temporary_file1_for_zip.csv
*** Writing the data to - temporary_file2_for_zip.csv
*** Input File name passed for zipping - ['temporary_file1_for_zip.csv', 'temporary_file2_for_zip.csv']
*** out_zip_file is - temporary.zip
*** Processing file temporary_file1_for_zip.csv
*** Processing file temporary_file2_for_zip.csv

実行結果

上記のコードを実行すると、以下のファイルが生成されます。

  • カレントディレクトリに temporary_file1_for_zip.csv が作成される
  • カレントディレクトリに temporary_file2_for_zip.csv が作成される
  • カレントディレクトリに temporary.zip が作成される

これで、複数のファイルを1つのZIPファイルにまとめて圧縮できました。ZIP_DEFLATED(DEFLATE圧縮)以外にも、zipfile.ZIP_STORED(無圧縮で格納のみ)、zipfile.ZIP_BZIP2zipfile.ZIP_LZMA などの圧縮方式も利用できるので、用途に応じて使い分けるとよいでしょう。

  1. LinuxでZipファイルを解凍する方法|GUIとコマンドラインの使い方を徹底解説

    Zipファイルは、ダウンロード速度が遅く1バイトでも節約が重要だった時代ほど頻繁には使われなくなりました。それでも今なお広く普及しているファイル形式の一つであり、いずれ開く必要に迫られることもあるでしょう。使用しているディストリビューションにもよりますが、Zipアーカイブの展開自体は比較的簡単です。とはいえ、より高度な操作方法や応用的なテクニックを知っておけば、いざというときにきっと役立ちます。GUIを使ってZipファイルを解凍する多くのLinuxデスクトップ環境では、Zipファイルの解凍は非常に簡単です。ファイルを右クリックすると複数のオプションが表示され、通常は「ここで展開」や「ここに解凍

  2. macOSでファイルを圧縮・解凍する方法|ZIP作成からパスワード設定まで徹底解説

    ZIPファイルとは、1つまたは複数のファイルやフォルダを1つのファイルにまとめて圧縮したものです。パソコンのストレージ容量を節約できるだけでなく、複数のファイルを整理して管理するのにも役立ちます。圧縮されたファイルはUSBメモリやメールでの送信も格段に簡単になり、サーバー上で配布されるソフトウェアの多くも、ストレージ容量を節約するためにZIP形式で提供されています。この記事では、macOSでファイルを圧縮(ZIP化)および解凍する具体的な手順を、基本操作から応用テクニックまでわかりやすく解説します。macOSでファイルを圧縮(ZIP化)する方法多くのオペレーティングシステムには、ファイルやフォ