使用 python3 中的 tar 文件模块从 tar 中提取文本文件
Extracting a text file from tar with tarfile module in python3
在 python 3.4 或更高版本中,是否有一种简单的方法可以从 tar
文件中提取文本文件作为文本 I/O 的文件对象?
我正在将我的 python2 代码修改为 python3,我发现 TarFile.extractfile
,它用于 return 带有文本 I/O 的文件对象],现在 return 是一个 io.BufferedReader
对象,它似乎有二进制 I/O。我的代码的另一部分需要一个文本 I/O,我需要以某种方式吸收这种变化。
我能想到的一种方法是用TarFile.extract
把文件写到一个目录下,然后用open
函数打开,但是不知道有没有办法获取文本I/O 直接流。
你可以使用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()
尝试 io.TextIOWrapper
包装 io.BufferedReader
。
在 python 3.4 或更高版本中,是否有一种简单的方法可以从 tar
文件中提取文本文件作为文本 I/O 的文件对象?
我正在将我的 python2 代码修改为 python3,我发现 TarFile.extractfile
,它用于 return 带有文本 I/O 的文件对象],现在 return 是一个 io.BufferedReader
对象,它似乎有二进制 I/O。我的代码的另一部分需要一个文本 I/O,我需要以某种方式吸收这种变化。
我能想到的一种方法是用TarFile.extract
把文件写到一个目录下,然后用open
函数打开,但是不知道有没有办法获取文本I/O 直接流。
你可以使用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()
尝试 io.TextIOWrapper
包装 io.BufferedReader
。