第八章:数据压缩与归档-tarfile:tar归档访问-从非文件源写数据

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()把数据写至归档。
运行结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43193719/article/details/89292735