The fileobj
argument of tarfile.open
serves exactly this purpose: you can pass any file-like object that support writting to it and tarfile
will happily use that instead of trying to reach out to the filesystem. Note that such files should be opened in binary mode and not in text mode (which tempfile.TemporaryFile
does by default).
Similarly, the first argument to zipfile.ZipFile
can be a file-like object.
So you could do:
with tempfile.TemporaryFile(suffix='.tar.gz') as f:
with tarfile.open(fileobj=f, mode='w:gz') as tar:
tar.add(…)
f.flush()
f.seek(0)
print(f.read())
Or
with tempfile.NamedTemporaryFile('wb', suffix='.tar.gz', delete=False) as f:
with tarfile.open(fileobj=f, mode='w:gz') as tar:
tar.add(…)
to keep f.name
on your filesystem and explore its content later.