stringio+tarfile
Peter Otten
__peter__ at web.de
Fri Jul 3 08:12:38 EDT 2009
superpollo wrote:
> thanks to the guys who bothered to answer me even using their chrystal
> ball ;-)
>
> i'll try to be more specific.
>
> yes: i want to create a tar file in memory, and add some content from a
> memory buffer...
>
> my platform:
>
> $ uname -a
> Linux fisso 2.4.24 #1 Thu Feb 12 19:49:02 CET 2004 i686 GNU/Linux
> $ python -V
> Python 2.3.4
>
> following some suggestions i modified the code:
>
> $ cat tar001.py
> import tarfile
> import StringIO
> sfo1 = StringIO.StringIO("one\n")
> sfo2 = StringIO.StringIO("two\n")
> tfo = StringIO.StringIO()
> tar = tarfile.open(fileobj=tfo , mode="w")
> ti = tar.gettarinfo(fileobj=tfo)
gettarinfo() expects a real file, not a file-like object.
You have to create your TarInfo manually.
> for sfo in [sfo1 , sfo2]:
> tar.addfile(fileobj=sfo , tarinfo=ti)
> print tfo
>
> and that's what i get:
>
> $ python tar001.py > tar001.out
> Traceback (most recent call last):
> File "tar001.py", line 7, in ?
> ti = tar.gettarinfo(fileobj=tfo)
> File "/usr/lib/python2.3/tarfile.py", line 1060, in gettarinfo
> name = fileobj.name
> AttributeError: StringIO instance has no attribute 'name'
>
> can you help?
I recommend that you have a look into the tarfile module's source code.
The following seems to work:
import sys
import time
import tarfile
import StringIO
sf1 = "first.txt", StringIO.StringIO("one one\n")
sf2 = "second.txt", StringIO.StringIO("two\n")
tf = StringIO.StringIO()
tar = tarfile.open(fileobj=tf , mode="w")
mtime = time.time()
for name, f in [sf1 , sf2]:
ti = tarfile.TarInfo(name)
ti.size = f.len
ti.mtime = mtime
# add more attributes as needed
tar.addfile(ti, f)
sys.stdout.write(tf.getvalue())
Peter
More information about the Python-list
mailing list