Search code examples
pythontry-except

Try except block python varies result


I am reading some .json files. Some of the files are empty. So I am using try-except block to read. If it is empty then except condition will be executed. My code snippet looks like this:

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

The code ran perfectly at the first couple of times or so, where it iterates the second for loop with jsondata["workItemList"]. But when I run later again, the second for loop doesn't iterate and all the iterations show the print statement inside except json empty.

Does try-except block have any state or specific behavior?? Do I need to delete or refresh something after running the first time to repeat again?


Solution

  • All you need is json.decoder.JSONDecodeError exception.

    It looks like this:

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

    More about in Json Docs

    Or you can handle error only when loading 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)
    

    You can read more about try/except in Python Documentation