3
4

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 5 years have passed since last update.

pythonでon-memoryにtar.gzを作る

Posted at
convert_str_to_tar_gz.py
import io
import tarfile
import gzip


def convert_str_to_tar_gz(input: str, name: str, encoding: str='utf-8') -> bytes:
    # 入力された文字列をBytesIOにする
    input_io = io.BytesIO(input.encode(encoding))
    # 出力用のBytesIOを用意
    output_io = io.BytesIO()
    # TarFileを用意
    tar = tarfile.TarFile(fileobj=output_io, mode='w')
    info = tarfile.TarInfo(name=name)
    info.size = input_io.getbuffer().nbytes
    tar.addfile(info, input_io)  # TarFileに追加する(info.size分input_ioから読み込まれる)
    # output_ioから結果を取得
    result = output_io.getvalue()
    tar.close()
    output_io.close()
    return gzip.compress(result)

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?