python - 在 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
解决方案
当你打电话时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))
推荐阅读
- c - 实施IFFT
- python - Pycharm Traceback(最近一次调用)中的 Anaconda 错误 - 导入 numpy
- r - facet_wrap 的配对数据
- php - 在 Woocommerce 单品页面上获取并显示税率
- javascript - 重置引导输入微调器单击按钮
- python - 我是否使用“rescale=1./255”?构建VGG-like CNN
- c - 如何将 .bin 文件转换为人类可读的字符串?
- rust - 如何使用多个级别的特征
- python - 如何在不引用旧列名且不创建新数据框的情况下更改列名?
- sql-server - 将 Excel 文件导入 SSMS 但文本被截断