【问题标题】:Python: Return a blank and continue for loop after exceptionPython:异常后返回空白并继续循环
【发布时间】:2021-12-27 01:21:55
【问题描述】:

我有一个 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))

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

【问题讨论】:

    标签: python exception


    【解决方案1】:

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

    【讨论】:

    • 谢谢!但对d.append([default row goes here]) 在做什么感到困惑
    • 我不知道列表应该有多少元素。所以我只是把它作为一个占位符,你可以用一个包含适当数量的空字符串的列表来替换它。
    • 啊,明白了!谢谢,这很有帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-01
    • 2023-01-13
    • 2019-09-05
    • 2020-07-01
    • 2018-03-20
    • 2015-08-19
    • 2021-03-25
    相关资源
    最近更新 更多