-2

I am trying to parse multiple sheets inside a spreadsheet from Google Sheets. Is running fine, except when it gets after the final sheet that cannot be found because it does not exist. As you can see I am doing that in a for loop with 200 iterations, but I would like to break the loop when the exception is raised.

My code:

def main_concat(id_file, n):
      import httplib2
      import os
      import pandas as pd
      import sys
      from apiclient import discovery

      try:

        discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'
                        'version=v4')
        service = discovery.build(
            'sheets',
            'v4',
            http=httplib2.Http(),
            discoveryServiceUrl=discoveryUrl,
            developerKey=key)

        spreadsheetId = id_file
        rangeName = f'Respuestas de formulario {n}!A1:L1000'
        result = service.spreadsheets().values().get(
            spreadsheetId=spreadsheetId, range=rangeName).execute()
        values = result.get('values', [])

        if not values:
            print('No data found.')
        else:
            
            df=pd.DataFrame(values)
        
        return df
      
      except SystemExit:
        print('No más hojas de formularios que extraer')
        

dfs=[]



for i in range(1,200):

  df=main_concat('1nRAte3AH0pvLMQTg-SEkiSsy4MONJnpTADOGoDLA', i)
  dfs.append(df)
alb
  • 185
  • 8

3 Answers3

1

Your function is returning a pandas dataframe normally. When the exception happens, the function is returning nothing (None) so just check the return value and if it's a None break the loop:

for i in range(1,200):

  df=main_concat('1nRAte3AH0pvLMQTg-SEkiSsy4MONJnpTADOGoDLA', i)
  if df is None:
    break

  dfs.append(df)

Not: Please use if __name__ == "__main__" too. See: https://stackoverflow.com/a/419185/2681662

Edit

After your comment to João Santos I understand that you have an unknown number of files and you are trying to access 200 of them and if an exception happens it means no more files available and you want to stop the loop.

That's not a good way for multiple reasons.

  1. What if for some other reasons your code fails. Now your loop would stop.
  2. What if you had more then 200 files. Your loop would stop at 200.

I think you need to find the file names and iterate over them. If it is not an option, at least you can use a while loop since you are breaking it anyway. So if there are more then 200 files your loop would work:

i = 0
while True:
  i += 1
  df=main_concat('1nRAte3AH0pvLMQTg-SEkiSsy4MONJnpTADOGoDLA', i)
  if df is None:
    break

  dfs.append(df)
MSH
  • 1,743
  • 2
  • 14
  • 22
1

Several options, two of which I'll highlight:

Check the return:

for i in range(1,200):

  df=main_concat('1nRAte3AH0pvLMQTg-SEkiSsy4MONJnpTADOGoDLA', i)
  if df is None:
    break

  dfs.append(df)

Other option is to actually raise the exception.

def main_concat(id_file, n):
      try:

        ...
        
      except SystemExit:
        print('No más hojas de formularios que extraer')
        raise
        
dfs=[]

try:
  for i in range(1,200):
    # can either catch and break, or just let it propagate.
    df=main_concat('1nRAte3AH0pvLMQTg-SEkiSsy4MONJnpTADOGoDLA', i)
    dfs.append(df)
except Exception:
  pass
saquintes
  • 1,074
  • 3
  • 11
  • thanks. I finally implemented the first one. The second one is a nice workaround too. Good to know for next times! – alb Oct 13 '21 at 10:47
0

Raise a general exception.

try:
    #code
except Exception as e:
    print(e)
João Santos
  • 194
  • 11
  • Hi, that does not break my loop. Let's say I have 19 sheets and my for loop is until 200. How do I break in iteration 20 without the need to write range(0,20) manually? – alb Oct 13 '21 at 10:29