LoginSignup
5
4

More than 5 years have passed since last update.

Pythonでtarアーカイブをメモリ上で解凍する方法

Last updated at Posted at 2018-02-23

いちいちファイルに書き出したくないときに使えるテクニック。デフォルトで用意されているモジュールtarfileを用います。

import tarfile

with tarfile.open("archive.tar.xz", mode="r:xz") as tar:
    for tarinfo in tar:
        if(tarinfo.isreg()):
            #bytesで格納
            binary = tar.extractfile(tarinfo).readline()
            #文字列に変換
            str = binary.decode("utf-8")
            print(str)

tar.extractfileの返り値がExFileObjectなので、readline()等でbytesに変換するのがポイント。そのあと文字列で使いたければデコードします。

訂正&補足:
この例だと1行しか読み取れません。1ファイル内に改行が含まれる場合は例えば、以下のようにします。

binary = b''.join(tar.extractfile(tarinfo).readlines())
5
4
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
5
4