1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

フォルダ内にあるすべてのzipファイルを解凍するスクリプトを作ってみた

Posted at

動機 ~無いなら作ればいいじゃない~

複数のzipファイルを入手したんだけれど、手動で1つずつ解凍するのが億劫だったので、「一括でzipファイルを解凍する」物を作ろうと思った。

仕様(?)

zipファイルと同じ名前のフォルダを作成し、その中に解凍するようにした。
標準のzipライブラリを使うことも考えたのだけれど、「7-zipのほうが高機能だろう。」という偏見があったので、7-zipの機能を使わせてもらった。

学び

リストの内報表記を使ってみた。
試行錯誤でこのような形になったのだけれど、慣れるまで時間がかかってしまった。
コードは書いてなんぼ。避けてた機能が多々あるので、これからは真摯に向き合っていきたい。
いい勉強になった。

コード

以下、作成したコード

Extract_ZipFiles.py
import os
import subprocess
import multiprocessing

# zipファイルの解凍
def extract_zip(zip_path, extract_dir):
    try:
        # 7-zip のパスを設定
        seven_zip_path = r"C:\Program Files\7-Zip\7z.exe" 

        # 7-zip コマンドを実行(解凍先にファイルが存在する場合は強制的に上書き。確認はスキップ)
        command = [seven_zip_path, "x", zip_path, f"-o{extract_dir}", "-y"]
        subprocess.run(command, check=True)

    except subprocess.CalledProcessError as e:  # 解凍失敗
        print(f"Error extracting {zip_path}: {e}")
    except FileNotFoundError:
        print("7-zip が見つかりません。パスを確認してください。") #7-zipが存在しない場合

def main():

    archive_dir = r"C:\Users\OkawaKohei\Documents\sample"  # 複数のzipが格納されているパスを設定。
    # ディレクトリの確認
    if not os.path.exists(archive_dir):
        print("Archive フォルダが見つかりません。")
        return

    zip_files = [
        (os.path.join(archive_dir, filename), os.path.join(archive_dir, filename[:-4]))
        for filename in os.listdir(archive_dir)
        if filename.endswith(".zip")
    ]
        
    with multiprocessing.Pool() as pool:        # プロセスのプール
        pool.starmap(extract_zip, zip_files)    # extract_zip 関数を並列実行

if __name__ == "__main__":
    main()

1
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?