Reputation: 19385
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...
Upvotes: -1
Views: 1522
Reputation: 19385
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)
Upvotes: 1