在电子表格中跳过空白单元格

时间:2015-02-19 21:24:15

标签: python

我有一个for循环,可以从网站上的电子表格中提取数据,并将数据写入文本文件。电子表格通常不会更新,因此是空白的。当电子表格为空白时,我的循环失败。如果失败,我将如何跳过循环?

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 个答案:

答案 0 :(得分:2)

aatable.findAll('tr')分配给变量data并检查if data以获取空列表:

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')

或使用try/except来抓住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