我的文件可能为空,也可能为空。目的是从文件中读取一个json对象,将其追加,然后将其写回到文件中。但是,如果文件为空,则json.load()失败。如何解决此问题而不必事先检查文件是否为空?
这是我当前的代码:
with open(filename, 'a+') as infile:
old_data = json.load(infile)
data = old_data + obj
with open(filename, 'w') as outfile:
json.dump(data, outfile)
错误消息是:
File "<stdin>", line 3, in <module>
File "/usr/lib/python3.6/json/__init__.py", line 299, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
File "/usr/lib/python3.6/json/__init__.py", line 354, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.6/json/decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.6/json/decoder.py", line 357, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
要扩展@pault注释,可以使用try / except,但是在缩进更好的块中它会更好地工作(可选,您也可以链接该with
语句):
from json.decoder import JSONDecodeError
with open(filename, 'a+') as infile, open(filename, 'w') as outfile:
try:
old_data = json.load(infile)
data = old_data + obj
json.dump(data, outfile)
except JSONDecodeError:
pass
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句