Search code examples
pythontarfile

Compress directory into tar.gz file in memory with python


Trying to compress a filesystem directory into a tar.gz file and keep it in memory. Why, because I don't want to pollute the filesystem with a temporary file.

I am looking into tarfile package but I don't seem to get it done:

import io
import tarfile

fo = io.BytesIO()
tar = tarfile.open(fileobj=fo, mode="w:gz")
tar.add(path)

Does not seem to work as I intend...


Solution

  • Solved with this snippet:

    import io
    import tarfile
    
    path = "/tmp/foodir" # this is a directory
    
    file_io = io.BytesIO()
    with tarfile.open(fileobj=file_io, mode="w|gz") as tar:
        arcname = os.path.basename(path) # keep path relative (optional)
        tar.add(path, arcname=arcname)
    file_io.seek(0)