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.
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
The solution in Python 3 uses
io.BytesIO
. Be sure to setTarInfo.size
to the length of the bytes, not the length of the string.Given a single string, the simplest solution is to call
.encode()
on it to obtain bytes. In this day and age you probably want UTF-8, but if the recipient is expecting a specific encoding, such as ASCII (i.e. no multi-byte characters), then use that instead.If you really need a writable string buffer, similar to the accepted answer by @Stefano Borini for Python 2, then the solution is to use
io.TextIOWrapper
over an underlyingio.BytesIO
buffer.You have to use TarInfo objects and the addfile method instead of the usual add method:
As Stefano pointed out, you can use
TarFile.addfile
andStringIO
.You'll probably want to fill other fields of
tarinfo
(e.g.mtime
,uname
etc.) as well.In my case I wanted to read from an existing tar file, append some data to the contents, and write it to a new file. Something like:
Extra code is needed for handling directories and links.
Just for the record:
StringIO objects have a .len property.
No need to seek(0) and do len(foo.buf)
No need to keep the entire string around to do len() on, or God forbid, do the accounting yourself.
( Maybe it did not at the time the OP was written. )
I would say it's possible, by playing with TarInfo e TarFile.addfile passing a StringIO as a fileobject.
Very rough, but works