用python3中的tarfile模块从tar中提取文本文件

用python3中的tarfile模块从tar中提取文本文件

问题描述:

是否有一种简单的方法可以从tar文件中提取文本文件作为python 3.4或更高版本中的文本I/O的文件对象?用python3中的tarfile模块从tar中提取文本文件

我修改我的python2代码python3,我发现TarFile.extractfile,其中用于返回文本文件对象的I/O,现在返回一个io.BufferedReader对象似乎有开关量I/O。我的代码的其他部分需要一个文本I/O,我需要以某种方式吸收这种变化。

我能想到的一种方法是使用TarFile.extract并将该文件写入一个目录,并通过open函数将其打开,但我想知道是否有办法直接获取文本I/O流。

尝试io.TextIOWrapper包裹io.BufferedReader

你可以使用getmembers()

import tarfile 
tar = tarfile.open("test.tar") 
tar.getmembers() 

之后,你可以使用extractfile()的成员提取物作为文件对象。只是一个例子

import tarfile,os 
import sys 
os.chdir("/tmp/foo") 
tar = tarfile.open("test.tar") 
for member in tar.getmembers(): 
    f=tar.extractfile(member) 
    content=f.read() 
    // do operations with your content 
    sys.exit() 
tar.close() 
+0

谢谢。内容是二元的。我的问题是如何获得文本I/O。 – norio