2014-12-01 2 views
2

파일이 있습니다 : "docs.tar.gz". tar 파일에는 네 번째 파일 인 "docs.json"이 있는데 필요한 파일은 4 개입니다. 볼 수 있습니다. tar 파일의 내용을 사용하여 :파이썬은 tar 아카이브 내의 파일을 읽습니다.

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

내가 네 번째 파일 내가 필요 년 - JSON 파일을 읽을 것입니다 방법은 ...없는 임은 contents.Thanks를 추출 후 진행합니다!

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

Mayby이 [anwser (http://stackoverflow.com/questions/8008829/extract-only-a-single-directory-from-tar) 유용 할 것이다. – Marcin

답변

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

'file'이라는 이름의 변수를 만드는 것은 좋은 습관이 아니라는 약간의 코멘트 Python –

+0

파일 "/usr/lib/python2.7/gzip.py", 줄 312, _read uncompress = self .decompress.decompress (buf) 오류 : 압축을 풀 때 오류 -3 : 유효하지 않은 리터럴/길이 코드 이것은 json 파일을 읽을 때 발생하는 오류입니다. –

+0

정말 옳습니다. 감사합니다 @ AlexanderStarostin – nathancahill

1

이 하나가 너무 작동합니다

관련 문제