Unzip file . gz with Python

Asked

Viewed 873 times

0

I’m using the code below that I took at this address.

But I’m not able to unzip files .gz. I’ve tried the library tarfile, but without success. Follow the code below:

from io import BytesIO
from urllib.request import urlopen
from zipfile import ZipFile
import pandas as pd


startdate = '20170130'
enddate = '20170207'
extension = '.zip'
daterange = pd.date_range(start=startdate, end=enddate)

for single_date in daterange:
   zipurl = 'ftp://ftp.bmf.com.br/MarketData/BMF/NEG_BMF_' + 
single_date.strftime('%Y%m%d') + extension
   try:
      with urlopen(zipurl) as zipresp:
          with ZipFile(BytesIO(zipresp.read())) as zfile:
              zfile.extractall()
      print("OK: {}".format(zipurl))
   except:
      print('ERRO: {}'.format(zipurl))

   print("="*5)
  • 1

    Which error appears?

  • I have to unzip files .gz. And this unzipped code .zip. I tried to replace it with gz, but it didn’t work out. Same programming errors.

1 answer

1


You can do this using libraries gzip and shutil, as in the example:

import gzip
import shutil

with gzip.open('file.gz', 'rb') as entrada:
    with open('file', 'wb') as saida:
        shutil.copyfileobj(entrada, saida)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.