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

More than 3 years have passed since last update.

Python ネストされたzipを全て解凍する

Last updated at Posted at 2021-05-08

2021/05/14 追記

既に解凍済のzipは解凍しないように制御処理を追加

Pythonでネスト(入れ子)されたzipファイルを全て解凍する

環境

  • Windows
  • Python3

コード

import os
import zipfile


PATH = 'path'


def extract(zipFile, dst):
    with zipfile.ZipFile(zipFile) as z:
        z.extractall(dst)


def func(path):
    # ///// point 1 /////
    for pathname, dirnames, filenames in os.walk(path):
        for filename in filenames:
            if filename.endswith('.zip'):
                if not os.path.exists(pathname + '/' + os.path.splitext(filename[0]):
                   zipFile = pathname + '/' + filename
                   dst = pathname + '/' + os.path.splitext(filename)[0]
                   extract(zipFile, dst)
                   # ///// point 2 /////
                   func(dst)


def main():
    func(PATH)


main()

コードのポイント

point 1

  • os.walkを使い, 指定パス以下を再帰的に探索. 記述量が少ない

point 2

  • zipファイル解凍後は, 解凍後のパスを再帰処理しネストされたzipやディレクトリも全て解凍/探索する
0
0
1

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?