首页 > 解决方案 > 尝试除了块python改变结果

问题描述

我正在阅读一些 .json 文件。有些文件是空的。所以我正在使用try-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")

该代码在前几次左右完美运行,它for使用jsondata["workItemList"]. 但是当我稍后再次运行时,第二个for循环不会迭代,并且所有迭代都会在 except 中显示 print 语句json empty

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

标签: pythontry-except

解决方案


你所需要的只是json.decoder.JSONDecodeError例外。

它看起来像这样:

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

更多关于Json 文档

或者您只能在加载 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 文档中阅读有关 try/except 的更多信息


推荐阅读