繁体   English   中英

Python:返回一个空白并在异常后继续循环

[英]Python: Return a blank and continue for loop after exception

我有一个 for 循环,我使用 API 密钥将一些值返回到 CSV 中。 我希望每次出现错误而不是代码中断时循环都返回一个空行。 我知道我需要使用continue但不确定如何为我得到的每个indexError插入一个空行。

我编写了一个名为get_data的函数,它从 API 返回响应文本。 所以使用它,这就是我试图为输入文件df运行的

d = []
try: 
    for i in range(len(df)):
        output = df.loc[i,"column_1"] 
        d.append(get_data(output))
        lat = pd.DataFrame(d)
        lat_lon= lat.apply(pd.Series)
        f = open('results.csv','w')
        lat_lon.to_csv('results.csv')
except IndexError: 
        print('ERROR at index {}: {!r}'.format(i, address))

我希望每次出现indexError时输出 csv 文件results.csv都留一个空行

try/except需要在循环内。 否则,您会在发生异常时中止整个循环。

此外,您不应该每次通过循环写入 CSV 文件。 d的完整内容写在最后。

d = []
for i in range(len(df)):
    try: 
        output = df.loc[i,"column_1"] 
        d.append(get_data(output))
    except IndexError: 
        print('ERROR at index {}: {!r}'.format(i, address))
        d.append([default row goes here])
lat = pd.DataFrame(d)
lat_lon= lat.apply(pd.Series)
f = open('results.csv','w')
lat_lon.to_csv('results.csv')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM