LoginSignup
0
0

【Python】zipファイルを一括で展開するコード

Posted at

zipファイルをまとめて抽出するコードを作成したので、
その備忘録としてこちらに記します。

本コードを記述するにあたり

Python公式ドキュメント
Pythonでディレクトリを(存在するかどうか確かめて存在しなかったら)作成する

を参照しました。
コードはpythonの標準ライブラリを使用しているため、追加で pip install を行う必要はありません。

本コード

extractZip.py
import os
import zipfile
from tkinter import *
from tkinter import filedialog


current_dir = os.path.dirname(__file__)
targets = filedialog.askopenfiles(initialdir=current_dir, filetypes=[('zip file', 'zip')])

for target in targets:
    target_folder = os.path.basename(target.name).split('.')[0]
    with zipfile.ZipFile(target.name, 'r') as zf:
        for file in zf.namelist():
            file_path = ''
            with zf.open(file) as f:
                contents = f.read()
                file_path = os.path.join(current_dir, target_folder, file)
                os.makedirs(os.path.dirname(file_path), exist_ok=True)
                with open(file_path, 'wb') as w:
                    w.write(contents)

簡単な説明

  • tkinter.filedialog.askopenfiles

上記コードを実行すると、ダイアログが開きます。展開したいzipファイルを選択し(複数ファイル可能)、「開く」を押下すると実行したPythonモジュールと同階層にzipファイル名と同じフォルダが作成され、その配下にアーカイブされたファイルが展開されます。

  • zipfile.ZipFile

with構文を用いると便利なのでこれを使用。読み込みモード('r')でzipファイルを読み込み、zipファイル内の各ファイルをフォルダ階層ごとに走査、フォルダ構造を再現しつつファイルを出力していきます。
なお、contents = f.read() はバイト列のため with open(file_path, 'wb') as w: のようにバイト書き込みモードを wb にしています。contents_decode = contents.decode()により文字列に直してから、書き込みモードwで出力するとしても問題ありません。

まとめ

さらっと記述できましたが、あると便利かなと思いました。
また、 os.makedirs(os.path.dirname(file_path), exist_ok=True)exist_ok=True にするとフォルダ作成がストレスフリーですね。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0