在 python 中读取 *.tar.gz 文件而不解压

yig*_*gal 4 python utf-8 python-3.x

在 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'
Run Code Online (Sandbox Code Playgroud)

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

Die*_*Epp 6

当你打电话时tarfile.open

tarfile.open('arhivename.tar.gz', encoding='utf-8')
Run Code Online (Sandbox Code Playgroud)

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

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

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