简体   繁体   中英

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...

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM