python tared文件夹流

2024-10-01 19:20:08 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有一种方法可以对文件夹进行tarred,并获得tarred流而不是tared文件? 我尝试过使用tar模块,但它直接返回tared文件。在

with tarfile.open("zipped.tar",'w|') as tar:
    for base_root, subFolders, files in os.walk('test'):
            for j in files:
                filepath = os.path.join(base_root,j)
                if os.path.isfile(filepath):
                    with open(filepath, 'rb') as file:
                        size = os.stat(filepath).st_size
                        info = tarfile.TarInfo()
                        info.size = size
                        info.name = filepath
                        if(size <= chunck_size):
                            data = file.read(info.size)
                            fobj = StringIO.StringIO(data)
                            tar.addfile(info, fobj)
                        else:
                            data = ""
                            while True:
                                temp_data = file.read(chunck_size)
                                if temp_data == '':
                                    break
                                data = data + temp_data
                            fobj = StringIO.StringIO(data)
                            tar.addfile(info, fobj) 

Tags: 文件infodatasizeifoswithtar
1条回答
网友
1楼 · 发布于 2024-10-01 19:20:08

根据the documentationopen可以采用fileobj参数:

If fileobj is specified, it is used as an alternative to a file object opened in binary mode for name. It is supposed to be at position 0.

所以你可以写这个,然后使用缓冲区对象。在

import io
buffer = io.BytesIO()
with tarfile.open("zipped.tar",'w|', fileobj=buffer) as tar:

相关问题 更多 >

    热门问题