python write string directly to tarfile

gatoatigrado picture gatoatigrado · Apr 11, 2009 · Viewed 17.4k times · Source

Is there a way to write a string directly to a tarfile? From http://docs.python.org/library/tarfile.html it looks like only files already written to the file system can be added.

Answer

Stefano Borini picture Stefano Borini · Apr 11, 2009

I would say it's possible, by playing with TarInfo e TarFile.addfile passing a StringIO as a fileobject.

Very rough, but works

import tarfile
import StringIO

tar = tarfile.TarFile("test.tar","w")

string = StringIO.StringIO()
string.write("hello")
string.seek(0)
info = tarfile.TarInfo(name="foo")
info.size=len(string.buf)
tar.addfile(tarinfo=info, fileobj=string)

tar.close()