python - 尝试除了块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
有任何状态或特定行为?第一次运行后是否需要删除或刷新某些内容才能再次重复?
解决方案
你所需要的只是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 的更多信息
推荐阅读
- bitcoind - 如何在比特币/莱特币闪电网络中创建 3 个中的 3 个多重签名地址
- hyperledger-fabric - 如何解码fabric中的块数据文件?
- python - 写满 Python 代码的 Latex 书的艰难工作流程
- android - 如何在 AOSP 中将默认位置服务设置为关闭
- angular - 静态组件未在 Angular 中刷新
- node.js - npm:找不到命令centos 7
- python - 无法在 Flask 的 html 标记中使用 url_for 转到另一个页面
- sftp - 使用代理的 RCurl sftp 连接
- java - 在 Java 中的 RedirectView 中设置标题
- java - 从 twitter4j 获取翻译数据