首页 > 解决方案 > 在 python 中读取 *.tar.gz 文件而不提取

问题描述

在 python 3 中,我试图读取驻留在 tar.gz 存档中的文件而不提取它们(意味着不将提取文件写入磁盘)。我找到了 tarfile 模块,这就是我写的(非常简化):

tar = tarfile.open('arhivename.tar.gz',encoding='utf-8')
for x in tar.getmembers():
    filelikeobject=tar.extractfile(x)
    #pass the filelikeobject to a third party function that accepts file-like object that read strings

    #the following lines are for debug:
    r=filelikeobject.read()
    print(type(r).__name__) #prints out 'bytes' - need 'str'

问题是,tar.extractfile(x) 返回一个文件对象,该对象在调用 read() 时返回字节。我需要它使用 utf-8 编码返回 str

标签: pythonpython-3.xutf-8

解决方案


当你打电话时tarfile.open

tarfile.open('arhivename.tar.gz', encoding='utf-8')

encoding参数控制文件名的编码,而不是文件内容的编码。参数控制文件内容的编码没有意义encoding,因为tar文件中的不同文件可以进行不同的编码。所以,一个 tar 文件实际上只包含二进制数据。

您可以通过使用模块中的 UTF-8 流阅读器包装文件来解码此数据codecs

import codecs
utf8reader = codecs.getreader('utf-8')
for name in tar.getmembers():
    fp = utf8reader(tar.extractfile(name))

推荐阅读