前言
作者在读取json文件的时候出现上述报错,起初以为是自己json文件有问题,但借助在线工具查看后发现没问题,就卡住了,在debug的过程中发现了json文件读取的一个小坑,在此分享一下
解决过程
原代码
with open(annotations_file) as f:
lenth = len(json.load(f)["annotations"])
#print(json.load(f)["annotations"])
if is_train:
data = json.load(f)["annotations"][0:int(lenth*0.8)]
else:
data = json.load(f)["annotations"][int(lenth*0.8):]
乍一看这个代码没有什么问题,但是作者发现lenth可以拿到数据,但是data执行时会报错,这就很奇怪,两行代码关于json文件读取的操作是一致的,为什么就是不行,后边作者加了print发现也会报错,因此得到结论,在一个with里不能加载两次
修改后代码
with open(annotations_file) as f:
data = json.load(f)["annotations"]
length = len(data)
if is_train:
data = data[:int(length * 0.8)]
else:
data = data[int(length * 0.8):]
问题解决