Python读取tar归档文件中的文件

4

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

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

我该如何读取第四个文件——即我需要的json文件?..在提取内容后,我无法继续进行。谢谢!


也许这个答案会有用。 - Marcin
3个回答

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

4

试试这个:

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

在编程中,使用变量名file并不是一个好的实践方法,因为Python已经占用了该名称。 - Alexander Starostin
以下是我读取JSON文件时遇到的错误信息:File "/usr/lib/python2.7/gzip.py", line 312, in _read uncompress = self.decompress.decompress(buf) error: Error -3 while decompressing: invalid literal/length code。 - ashwin shanker
看起来是一个损坏的文件 @ashwinshanker - nathancahill
@ nathancahill..看起来文件太大无法打开-不过还是谢谢! - ashwin shanker

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}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接