python write string directly to tarfile python write string directly to tarfile python python

python write string directly to tarfile


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

Very rough, but works

import tarfileimport StringIOtar = 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()


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

import tarfile, StringIOdata = '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.


I found this looking how to serve in Django a just created in memory .tgz archive, may be somebody else will find my code usefull:

import tarfilefrom io import BytesIOdef serve_file(request):    out = BytesIO()    tar = tarfile.open(mode = "w:gz", fileobj = out)    data = 'lala'.encode('utf-8')    file = BytesIO(data)    info = tarfile.TarInfo(name="1.txt")    info.size = len(data)    tar.addfile(tarinfo=info, fileobj=file)    tar.close()    response = HttpResponse(out.getvalue(), content_type='application/tgz')    response['Content-Disposition'] = 'attachment; filename=myfile.tgz'    return response