Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unpack bz2 url without temporary file in python

Tags:

python

bzip2

I want to unpack data from bz2 url directly to target file. Here is the code:

filename = 'temp.file'  
req = urllib2.urlopen('http://example.com/file.bz2')
CHUNK = 16 * 1024
with open(filename, 'wb') as fp:
  while True:
    chunk = req.read(CHUNK)
    if not chunk: break
    fp.write(bz2.decompress(chunk)) 
fp.close()

Error on bz2.decompress(chunk) - ValueError: couldn't find end of stream

like image 227
Иван Петров Avatar asked Jan 09 '23 06:01

Иван Петров


2 Answers

Use bz2.BZ2Decompressor to do sequential decompression:

filename = 'temp.file'  
req = urllib2.urlopen('http://example.com/file.bz2')
CHUNK = 16 * 1024

decompressor = bz2.BZ2Decompressor()
with open(filename, 'wb') as fp:
    while True:
        chunk = req.read(CHUNK)
        if not chunk:
            break
        fp.write(decompressor.decompress(chunk))
req.close()

BTW, you don't need to call fp.close() as long as you use with statement.

like image 156
falsetru Avatar answered Jan 16 '23 20:01

falsetru


Here's a more direct and efficient way using requests in streaming mode:

req = requests.get('http://example.com/file.bz2', stream=True)
with open(filename, 'wb') as fp:
    shutil.copyfileobj(req.raw, fp)
like image 38
John Zwinck Avatar answered Jan 16 '23 22:01

John Zwinck