Python在tar档案中读取文件

时间:2014-12-01 01:05:38

标签: python tar

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

import tarfile
tar=tarfile.open("docs.tar.gz")
tar.getmembers()

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

3 个答案:

答案 0 :(得分:3)

试试这个:

import tarfile
tar = tarfile.open("docs.tar.gz")
f = tar.extractfile("docs.json")

# do something like f.read()
# since your file is json, you'll probably want to do this:

import json
json.loads(f.read())

答案 1 :(得分:2)

这个也可以。

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()

答案 2 :(得分:0)

例如,使用Python3的上下文管理器的一个JSON文件:

$ cat myfile.json
{
    "key1": 1,
    "key2": 2,
    "key3": null
}

被压缩

tar czvf myfile.json.tar.gz myfile.json

并且可以像这样提取

import tarfile
import json

tar_file_name = "myfile.json.tar.gz"
data_file_name = "myfile.json"
with tarfile.open(tar_file_name, "r:gz") as tar:
    with tar.extractfile(data_file_name) as f:
        j = json.loads(f.read())

print(j)
# {'key1': 1, 'key2': 2, 'key3': None}
相关问题