python3 tarfile内存内打包文件

# -*- coding: utf-8 -*-
import tarfile
import os
from io import BytesIO,StringIO
def tarDict(dict1):
	fgz = BytesIO()
	tar = tarfile.open(mode="w",fileobj=fgz)
	ks=dict1.keys()
	for key in ks:
		tarinfo=tarfile.TarInfo(name=key)
		f1=BytesIO(dict1[key].encode())
		tarinfo.size=len(f1.read())
		f1.seek(0)
		tar.addfile(tarinfo,fileobj=f1)
	tar.close()
	return fgz
def output(fgz):
	f=open("output.tar","w")
	fgz.seek(0)
	f.write(fgz.read().decode())
	f.close()
byteio=tarDict({"a.txt":"aaaaaaaaaaaa","b.txt":"bbbbbbbbbbbbb"})
output(byteio)

你可能感兴趣的:(python)