6

I have a file:"docs.tar.gz".The tar file has 4 files inside of which the fourth file is "docs.json" which is what I need.Im able to view the contents of the tar file using:

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

How would I read the fourth file -the json file that I need?..Im unable to proceed after extracting the contents.Thanks!

1
  • Mayby this anwser will be useful. Commented Dec 1, 2014 at 1:13

3 Answers 3

5

Try this:

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())
Sign up to request clarification or add additional context in comments.

4 Comments

a little comment that it's not a good practice to create variable with the name file, it's taken by Python
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 This is the error I get though when i read the json file
Looks like a corrupt file @ashwinshanker
@ nathancahill..Looks like the file was too big to open-thanks anyway!
5

This one will work too.

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

Comments

1

As an example using Python3's context managers, a JSON file like this:

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

is compressed with

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

and can be extracted like this

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}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.