0

I have a for loop that pulls data from a spreadsheet on a website and writes the data to a text file. It is common that the spread sheet is not updated and therefore blank. When the spreadsheet is blank my loop fails. How would I skip the loop in the event that it fails?

for row in aatable.findAll('tr')[1:]:
     items = row.text.replace(u"kn","") # remove kn so items line up when unpacking
     time, ais_source, speed_km, lat, lon, course = items.split()[1:7]
     data = items.split()[1:7]
     text_file.write(str(data)+ ",Adams Challenge"+'\n')
1
  • can you give an example of what row.text contains exactly normally and when it is 'blank'? Do you mean it would be an empty string?
    – Stuart
    Feb 19, 2015 at 21:56

1 Answer 1

2

Assign aatable.findAll('tr') to a variable data and check if data to catch an empty list:

data = aatable.findAll('tr')
if data: # will be False for []
    for row in data[1:]:
         items = row.text.replace(u"kn","") # remove kn so items line up when unpacking
         time, ais_source, speed_km, lat, lon, course = items.split()[1:7]
         data = items.split()[1:7]
         text_file.write(str(data)+ ",Adams Challenge"+'\n')

Or use a try/except to catch the ValueError:

try:
    for row in aatable.findAll('tr')[1:]:
         items = row.text.replace(u"kn","") # remove kn so items line up when unpacking
         time, ais_source, speed_km, lat, lon, course = items.split()[1:7]
         data = items.split()[1:7]
         text_file.write(str(data)+ ",Adams Challenge"+'\n')
except ValueError:
    pass
5
  • I still get an error ValueError: need more than 4 values to unpack on the line time, ais_source, etc..
    – risail
    Feb 19, 2015 at 21:43
  • @Dan, that has nothing to do with getting an empty list, that is because there are not 6 elements in items.split()[1:7], have you tried printing items.split()? Feb 19, 2015 at 21:45
  • so did I phrase the question wrong? I still want to skip the loop when the elements are empty
    – risail
    Feb 19, 2015 at 21:46
  • I would like it to proceed if there is not data and if there is I want it to write it to the text file.This worked up until I noticed that a spreadsheet was blank.
    – risail
    Feb 19, 2015 at 21:52
  • 1
    @Dan, my mistake, I just realised you are slicing so we need to catch a ValueError in the try/except. I edited Feb 19, 2015 at 21:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.