Create TarFile using string buffers

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Mon Mar 19 18:18:50 EDT 2007


En Mon, 19 Mar 2007 16:06:39 -0300, aurora00 at gmail.com  
<aurora00 at gmail.com> escribió:

> I have a program that generates a number of files that will be
> packaged into a tarball. Can I stream the content into TarFile without
> first writing them out to the file system? All add(), addfile() and
> gettarinfo() seems to assume there is a file in the disk. But for me I
> seems inefficient to write all the content to the disk and then have
> it read back by the TarFile module.

You can create a TarInfo object directly, and use addfile with a StringIO  
object:

import tarfile
 from cStringIO import StringIO

data = "Some text, maybe containing\ntwo or more lines\n" + "The quick  
brown fox jumps over the lazy dog\n" * 20
fobj = StringIO(data)

tar = tarfile.open("sample.tar", "w")
tarinfo = tarfile.TarInfo("foo.txt")
tarinfo.size = len(data)
tar.addfile(tarinfo, fobj)
tar.close()

tar = tarfile.open("sample.tar", "r")
tar.list()
foo = tar.extractfile("foo.txt")
data_read = foo.read()
print "foo.txt:\n%s" % data_read
tar.close()
assert data == data_read


-- 
Gabriel Genellina




More information about the Python-list mailing list