【问题标题】:Try and except whilst trying to writerow in Python尝试在 Python 中编写时除外
【发布时间】:2020-06-14 16:54:35
【问题描述】:

我有以下代码在以下代码的条形码循环部分引发超出范围的错误。

for each in data['articles']:
         f.writerow([each['local']['name'],
         each['information'][0]['barcodes'][0]['barcode']])

我写了一个 try and except 来捕获和处理当我正在解析的 json 中不存在条形码时,这在使用打印功能的测试期间工作得很好,但是我在尝试时遇到了一些麻烦,除了在工作时试图写入 csv 文件。

有没有人有任何建议或其他方法我可以尝试让它发挥作用。

在使用 print 进行测试时,我的尝试和接受如下:

   for each in data['articles']:
          print(each['local']['name'])
          try:
                print(each['information'][0]['barcodes'][0]['barcode'])
          except: 
                "none"

非常感谢任何帮助!

【问题讨论】:

  • 在没有条码的情况下,你想在csv中写入什么?你想完全跳过那一行,还是写一些占位符,或者写一个有名称但没有条形码的行?
  • 当没有条形码时,我希望有“none”。

标签: python json csv for-loop exception


【解决方案1】:

正如 komatiraju032 指出的那样,一种方法是通过get(),尽管如果字典的不同元素可能具有空/不正确的值,则为每个元素提供默认值可能会变得笨拙。要通过try/except 执行此操作,您可以这样做:

for each in data['articles']:
    row = [each['local']['name']]
    try:
        row.append(each['information'][0]['barcodes'][0]['barcode'])
    except (IndexError, KeyError):
        row.append("none")
    f.writerow(row)

这将为您提供 "none" 替换值,无论这些列表/字典中的哪个缺少请求的索引/键,因为这些查找中的任何一个都可能是 raise,但它们都会以相同的 @987654326 结束@。

【讨论】:

    【解决方案2】:

    使用dict.get() 方法。如果密钥不存在,它将返回None

    res = each['information'][0]['barcodes'][0].get('barcode')
    

    【讨论】:

      猜你喜欢
      • 2018-07-04
      • 1970-01-01
      • 1970-01-01
      • 2021-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多