【发布时间】: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 open和json.load()行。 -
另外,
outPath来自哪里?是不是在这段代码上面定义的? -
outPath只是我保存结果的目录。所以要使try块更小。我如何使用jsondata如果 1. 尝试没有给出错误。 2. try 报错?
标签: python try-except