【发布时间】:2018-11-13 20:28:04
【问题描述】:
用于将字典元素转换为 Json 并写入文件,
with open(filename,'w') as f:
if(os.stat(f).st_size == 0):
json.dump(new_data, f)
else:
data = json.load(f)
data.update(new_data)#adding a new dictionary
json.dump(data, f)
我只能将一个 json 写入文件。当我想读取现有文件然后附加另一组字典时,我无法做到。
Getting ValueError: No JSON object could be decoded尝试
json.loads(f), json.load(f)
【问题讨论】:
-
奇怪,我不希望你得到
ValueError,我希望你得到IOError: File not open for reading。你能提供一个minimal reproducible example吗? -
是的,如果我以 w+ 形式打开,我会忽略文件未打开错误,但每次写入新的 json 时,即使文件存在于同一位置。上述代码中的打印数据显示无。所以问题是 data = json.load(f) 没有发生
-
我可以保证
f的大小为0字节,因为任何以'w'模式打开的文件都会被截断为0字节。 -
您发布的代码显然不是引发此异常的代码-
os.stat()采用路径,而不是file对象-,即使您将os.stat(f)替换为os.stat(f.name),@ 987654331@ 在此处始终为零,因为以写入模式打开的文件会立即被截断。
标签: python json python-2.7 file dictionary