LoginSignup
5
4

More than 3 years have passed since last update.

Pythonでzipファイルから特定の拡張子のファイルを抽出する

Last updated at Posted at 2019-07-15

概要

zipファイルから特定の拡張子ファイルのみ抽出したいことが何度かあったので、Pythonで実装しました。

例えば以下のような構成のzipファイルがあるとします。

test.zip
$ tree
.
├── 01
│   └── 01
│       └── a.txt
├── 02
│   ├── b.txt
│   └── c.txt
└── 03
    └── 01
        ├── 01
        │   └── d.txt
        ├── 02
        │   └── e.txt
        └── 03
            └── 01
                ├── f.txt
                └── g.txt

9 directories, 7 files

ここから以下のように1つのディレクトリにテキストファイルを抽出します。

$ tree
.
├── a.txt
├── b.txt
├── c.txt
├── d.txt
├── e.txt
├── f.txt
└── g.txt

treeコマンドのインストール

macでは、treeコマンドを以下コマンド実行でインストールできます。

$ brew install tree

zipファイルから特定の拡張子のファイルを抽出する

以下のコードを実行すると、テキストファイルが抽出されます。
extensionに代入する文字列を抽出したい拡張子にすれば、その拡張子のファイルのみ抽出できます。


import os
import zipfile
import shutil
extension = '.txt'
os.mkdir("./extract_txt/")
my_zip = zipfile.ZipFile('test.zip')
my_zip.extractall()
for file in my_zip.namelist():
    if my_zip.getinfo(file).filename.endswith(extension):
        shutil.move(file, "./extract_txt/")

抽出したテキストファイルを1つにまとめるときは、以下のコマンドを実行します。

$ cat *.txt > all.txt

参考

zipfile --- ZIP アーカイブの処理 — Python 3.7.4 ドキュメント
shutil --- 高水準のファイル操作 — Python 3.7.4 ドキュメント

5
4
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
5
4