Python 读取 tar 存档中的文件

ash*_*ker 4 python tar

我有一个文件:“docs.tar.gz”。tar 文件有 4 个文件,其中第四个文件是“docs.json”,这是我需要的。我可以使用以下命令查看 tar 文件的内容:

import tarfile
tar=tarfile.open("docs.tar.gz")
tar.getmembers()
Run Code Online (Sandbox Code Playgroud)

我将如何读取第四个文件 - 我需要的 json 文件?..提取内容后我无法继续。谢谢!

Ste*_*Lin 5

这个也可以。

import tarfile
tar = tarfile.open("docs.tar.gz")
files = tar.getmembers()
f = tar.extractfile(files[0]) # if your docs.json is in the 0th position
f.readlines()
Run Code Online (Sandbox Code Playgroud)