Suraj
Suraj

Reputation: 2477

How to catch the bad zip file error in python?

I am trying to extract the stock data for the past month and ran into this error when my code tries to extract stock data on days where there was no trading.

The code stops execution on datetime.date(2020, 7, 26) which was a Sunday and so there was no stock trade.

My code :

import datetime
from datetime import date
import pandas as pd

from nsepy.history import get_price_list
today = date.today()

yesterday = today - datetime.timedelta(days=1)
bhav_copy = get_price_list(dt=yesterday)
for i in range(1,30):
    date_ = yesterday - datetime.timedelta(days=i)
    try:
        prices = get_price_list(dt=date_)
    except BadZipFile as e:
        continue
    bhav_copy = bhav_copy.append(prices)

Error :

---------------------------------------------------------------------------
BadZipFile                                Traceback (most recent call last)
<ipython-input-108-37d75cc40921> in <module>
     13     try:
---> 14         prices = get_price_list(dt=date_)
     15     except BadZipFile as e:

~/anaconda3/lib/python3.7/site-packages/nsepy/history.py in get_price_list(dt, series)
    323     res = price_list_url(yyyy, MMM, dt.strftime("%d%b%Y").upper())
--> 324     txt = unzip_str(res.content)
    325     fp = six.StringIO(txt)

~/anaconda3/lib/python3.7/site-packages/nsepy/commons.py in unzip_str(zipped_str, file_name)
    121 
--> 122     zf = zipfile.ZipFile(file=fp)
    123     if not file_name:

~/anaconda3/lib/python3.7/zipfile.py in __init__(self, file, mode, compression, allowZip64, compresslevel)
   1257             if mode == 'r':
-> 1258                 self._RealGetContents()
   1259             elif mode in ('w', 'x'):

~/anaconda3/lib/python3.7/zipfile.py in _RealGetContents(self)
   1324         if not endrec:
-> 1325             raise BadZipFile("File is not a zip file")
   1326         if self.debug > 1:

BadZipFile: File is not a zip file

During handling of the above exception, another exception occurred:

NameError                                 Traceback (most recent call last)
<ipython-input-108-37d75cc40921> in <module>
     13     try:
     14         prices = get_price_list(dt=date_)
---> 15     except BadZipFile as e:
     16         continue
     17     bhav_copy = bhav_copy.append(prices)

NameError: name 'BadZipFile' is not defined

I would try to use a try and catch block. I imported the BadZipFile module, but run into errors when i try to catch the exception.

Below is the piece of code after the for loop, I guess I don't know how to use try and catch here, any help would be appreciated.

Upvotes: 1

Views: 4416

Answers (1)

Sam Morgan
Sam Morgan

Reputation: 3308

You need to import the error you're trying to catch:

from zipfile import BadZipFile

Upvotes: 3

Related Questions