【问题标题】:Try except block python varies result尝试除了块python改变结果
【发布时间】:2021-09-22 23:28:25
【问题描述】:

我正在阅读一些 .json 文件。有些文件是空的。所以我使用try-except 块来阅读。 如果它为空,则将执行除条件。我的代码 sn-p 如下所示:

exec = True
for jsonidx, jsonpath in enumerate(jsonList):
    print("\n")
    print(">>> Reading {} of {} json file: {}".format(jsonidx, len(jsonList), os.path.basename(jsonpath)))
    try:
        with open(jsonpath, "r") as read_file:
            jsondata = json.load(read_file)
        outPath = r'{}'.format(outPath)
        dicomPath = os.path.join(outPath, 'dicoms')
        nrrdPath = os.path.join(outPath, 'nrrds')
        if exec: # if you want to execute the move
            if not os.path.isdir(outPath):  # if the outPath directory doesn't exist.
                 os.mkdir(outPath)
                 os.mkdir(dicomPath)
                 os.mkdir(nrrdPath)
        thisJsonDcm = []
        for widx, jw in enumerate(jsondata['workItemList']):
            # print('\n')
            print('-------------------- Extracting workitem #{} --------------------'.format(widx))
            seriesName = jw['imageSeriesSet'][0]['seriesLocalFolderName']   # this is dicom folder whole path
            thisJsonDcm.append(seriesName)
   except:
        print("Json empty")

代码在前几次左右完美运行,它使用jsondata["workItemList"] 迭代第二个for 循环。 但是当我稍后再次运行时,第二个for 循环不会迭代,并且所有迭代都显示除了json empty 之外的内部打印语句。

try-except 块是否有任何状态或特定行为?第一次运行后是否需要删除或刷新某些内容才能再次重复?

【问题讨论】:

  • try 块太大了。任何数量的错误都可能潜伏在那里,与空的 json 文件完全无关。
  • json.decoder.JSONDecodeError 应该处理唯一的 json 读取错误吗? @Tikhon 建议 是的,try 块“太大”我同意。有没有更聪明的方法来处理这个问题?我需要读取 json 文件并执行一些工作。
  • 一般情况下,您希望使try 块尽可能小。使该块覆盖with openjson.load() 行。
  • 另外,outPath 来自哪里?是不是在这段代码上面定义的?
  • outPath 只是我保存结果的目录。所以要使try 块更小。我如何使用jsondata 如果 1. 尝试没有给出错误。 2. try 报错?

标签: python try-except


【解决方案1】:

您只需要json.decoder.JSONDecodeError 异常。

看起来像这样:

try:
    pass
    """Some stuff with json..."""
except json.decoder.JSONDecodeError:
    print("Json empty")

更多关于Json Docs

或者你只能在加载json时处理错误

exec = True
for jsonidx, jsonpath in enumerate(jsonList):
    print("\n")
    print(">>> Reading {} of {} json file: {}".format(jsonidx, len(jsonList), os.path.basename(jsonpath)))
    with open(jsonpath, "r") as read_file:
        try:
            jsondata = json.load(read_file)
        except json.decoder.JSONDecodeError:
            print("Json empty")
            continue
    outPath = r'{}'.format(outPath)
    dicomPath = os.path.join(outPath, 'dicoms')
    nrrdPath = os.path.join(outPath, 'nrrds')
    if exec: # if you want to execute the move
         if not os.path.isdir(outPath):  # if the outPath directory doesn't exist.
             os.mkdir(outPath)
             os.mkdir(dicomPath)
             os.mkdir(nrrdPath)
    thisJsonDcm = []
    for widx, jw in enumerate(jsondata['workItemList']):
        # print('\n')
        print('-------------------- Extracting workitem #{} --------------------'.format(widx))
        seriesName = jw['imageSeriesSet'][0]['seriesLocalFolderName']   # this is dicom folder whole path
        thisJsonDcm.append(seriesName)

您可以在Python Documentation 中阅读有关 try/except 的更多信息

【讨论】:

  • 第二种情况,for语句从哪里来?我处理 json 文件的块。
  • 是的,pass 不是必需的。此解决方案仅在文件为空或 json 在文件中无效时处理错误,所有其他错误将正常引发。如果您只想检查文件是否为空,您可以先读取它并与''if f.read().strip() == '':)进行比较
  • 我刚刚用完整代码更新了第二个解决方案
  • 是的,如果文件为空,则需要进行下一次迭代:只需将continue放在print("Json empty")之后即可
猜你喜欢
  • 1970-01-01
  • 2013-04-25
  • 2015-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-29
  • 2019-08-13
  • 2019-01-29
相关资源
最近更新 更多