8.4.6 从非文件源写数据
有时可能需要将数据从内存直接写至一个文档。并不是将数据先写入一个文件,然后再把这个文件增加到归档,可以使用addfile()从一个返回字节的打开的类似文件句柄添加数据。
import io
import tarfile
text = 'This is the data to write to the archive.'
data = text.encode('utf-8')
with tarfile.open('addfile_string.tar',mode='w') as out:
info = tarfile.TarInfo('made_up_file.txt')
info.size = len(data)
out.addfile(info,io.BytesIO(data))
print('Contents:')
with tarfile.open('addfile_string.tar',mode='r') as t:
for member_info in t.getmembers():
print(member_info.name)
f = t.extractfile(member_info)
print(f.read().decode('utf-8'))
首先构造一个TarInfo对象,可以为归档成员指定所需的任何名字。设置大小之后,以一个BytesIO缓冲区作为数据源,使用addfile()把数据写至归档。
运行结果: