尝试除块 python 不同的结果

Try except block python varies result

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

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 块是否有任何状态或特定行为?我是否需要在 运行 第一次重复之后删除或刷新某些内容?

您只需要 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 的更多信息