views:

755

answers:

3

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.

+5  A: 

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()
Stefano Borini
+3  A: 

As Stefano pointed out, you can use TarFile.addfile and StringIO.

import tarfile, StringIO

data = 'hello, world!'

tarinfo = tarfile.TarInfo('test.txt')
tarinfo.size = len(data)

tar = tarfile.open('test.tar', 'a')
tar.addfile(tarinfo, StringIO.StringIO(data))
tar.close()

You'll probably want to fill other fields of tarinfo (e.g. mtime, uname etc.) as well.

avakar
is the "As Stefano pointed out" an edit? Otherwise, I don't see what you're doing differently. Thanks for the response all the same.
gatoatigrado
I think Stefano haven't had any code posted at the time I wrote my response, he only noted that TarFile.addfile and StringIO can be used. My memory is little blurred, though.
avakar
+1  A: 

You have to use TarInfo objects and the addfile method instead of the usual add method:

from StringIO import StringIO
from tarfile import open, TarInfo

s = "Hello World!"
ti = TarInfo("test.txt")
ti.size = len(s)

tf = open("testtar.tar", "w")
tf.addfile(ti, StringIO(s))
Eli Courtwright