python - How do I to turn my .tar.gz file into a file-like object for shutil.copyfileobj? -
my goal extract file out of .tar.gz
file without extracting out sub directories precede desired file. trying module method off question. asked question of own seemed answer thought work didn't work fully.
in short, shutil.copyfileobj
isn't copying contents of file.
my code now:
import os import shutil import tarfile import gzip tarfile.open('rtlog_20150425t152948.gz', 'r:*') tar: member in tar.getmembers(): filename = os.path.basename(member.name) if not filename: continue source = tar.fileobj target = open('out', "wb") shutil.copyfileobj(source, target)
upon running code file out
created however, file empty. know file wanted extract does, in fact, have lots of information (approximately 450 kb). print(member.size)
returns 1564197
.
my attempts solve unsuccessful. print(type(tar.fileobj))
told me tar.fileobj
<gzip _io.bufferedreader name='rtlog_20150425t152948.gz' 0x3669710>
.
therefore tried changing source
to: source = gzip.open(tar.fileobj)
raised following error:
traceback (most recent call last): file "c:\users\dzhao\desktop\123456\444444\blah.py", line 15, in <module> shutil.copyfileobj(source, target) file "c:\python34\lib\shutil.py", line 67, in copyfileobj buf = fsrc.read(length) file "c:\python34\lib\gzip.py", line 365, in read if not self._read(readsize): file "c:\python34\lib\gzip.py", line 433, in _read if not self._read_gzip_header(): file "c:\python34\lib\gzip.py", line 297, in _read_gzip_header raise oserror('not gzipped file') oserror: not gzipped file
why isn't shutil.copyfileobj
copying contents of file in .tar.gz?
fileobj
isn't documented property of tarfile
. it's internal object used represent whole tar file, not specific current file.
use tarfile.extractfile()
file-like object specific member:
… source = tar.extractfile(member) target = open("out", "wb") shutil.copyfile(source, target)
Comments
Post a Comment