如何在Python3中将字符串添加到tarfile [英] How does one add string to tarfile in Python3
问题描述
我在将str
添加到python中的tar归档文件时遇到问题.在python 2中,我使用了这样的方法:
I have problem adding an str
to a tar arhive in python. In python 2 I used such method:
fname = "archive_name"
params_src = "some arbitrarty string to be added to the archive"
params_sio = io.StringIO(params_src)
archive = tarfile.open(fname+".tgz", "w:gz")
tarinfo = tarfile.TarInfo(name="params")
tarinfo.size = len(params_src)
archive.addfile(tarinfo, params_sio)
与该此处中的内容基本相同. 运作良好.但是,转到python 3时,它崩溃了,并导致以下错误:
Its essentially the same what can be found in this here. It worked well. However, going to python 3 it broke and results with the following error:
File "./translate_report.py", line 67, in <module>
main()
File "./translate_report.py", line 48, in main
archive.addfile(tarinfo, params_sio)
File "/usr/lib/python3.2/tarfile.py", line 2111, in addfile
copyfileobj(fileobj, self.fileobj, tarinfo.size)
File "/usr/lib/python3.2/tarfile.py", line 276, in copyfileobj
dst.write(buf)
File "/usr/lib/python3.2/gzip.py", line 317, in write
self.crc = zlib.crc32(data, self.crc) & 0xffffffff
TypeError: 'str' does not support the buffer interface
说实话,我很难理解它的来源,因为我没有将任何str
馈入tarfile
模块,直到返回构造StringIO
对象的位置.
我知道StringIO
和str
,字节等的含义从python 2变为3,但是我没有看到错误,也无法提出更好的逻辑来解决此任务.
To be honest I have trouble understanding where it comes from since I do not feed any str
to tarfile
module back to the point where I do construct StringIO
object.
I know the meanings of StringIO
and str
, bytes and such changed a bit from python 2 to 3 but I do not see a mistake and cannot come up with better logic to solve this task.
我精确地创建StringIO
对象,以围绕要添加到存档中的字符串提供缓冲方法.然而,令我惊讶的是某些str
没有提供它.最重要的是,在似乎负责校验和计算的行周围引发了异常.
I create StringIO
object precisely to provide buffer methods around the string I want to add to the archive. Yet it strikes me that some str
does not provide it. On top of it the exception is raised around lines that seem to be responsible for checksum calculations.
有人可以解释一下我所缺少的知识吗,或者至少可以举一个例子,说明如何在不向文件系统中创建中间文件的情况下向tar归档文件添加简单的str
.
Can some one please explain what I am miss-understanding or at least give an example how to add a simple str
to the tar archive with out creating an intermediate file on the file-system.
推荐答案
写入文件时,您需要将unicode数据显式编码为字节. StringIO
对象不会为您执行此操作,这是一个 text 内存文件.请使用io.BytesIO()
并进行编码:
When writing to a file, you need to encode your unicode data to bytes explicitly; StringIO
objects do not do this for you, it's a text memory file. Use io.BytesIO()
instead and encode:
params_sio = io.BytesIO(params_src.encode('utf8'))
当然可以根据数据调整编码.
Adjust your encoding to your data, of course.
这篇关于如何在Python3中将字符串添加到tarfile的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!