tar
gzip
Python3
tar.gz

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

More than 1 year has passed since last update.
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)

参考

https://docs.python.org/3.6/library/tarfile.html

https://docs.python.org/3/library/gzip.html

https://docs.python.org/3/library/io.html

https://stackoverflow.com/questions/26827055/python-how-to-get-iobytes-allocated-memory-length

https://stackoverflow.com/questions/740820/python-write-string-directly-to-tarfile

https://stackoverflow.com/questions/8858414/using-python-how-do-you-untar-purely-in-memory