Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python write string directly to tarfile

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.

like image 442
gatoatigrado Avatar asked Apr 11 '09 21:04

gatoatigrado


2 Answers

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() 
like image 138
Stefano Borini Avatar answered Oct 02 '22 13:10

Stefano Borini


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.

like image 29
avakar Avatar answered Oct 02 '22 14:10

avakar