Python 打开文件有时会导致json.decoder.jsondeCoderror
我有一个用新内容更新并每小时保存的文件:Python 打开文件有时会导致json.decoder.jsondeCoderror,python,json,Python,Json,我有一个用新内容更新并每小时保存的文件: with open('data.txt','w') as outfile: json.dump(data,outfile) 然后,我在任何给定时间读取此文件: with open('data.txt') as json_file: data = json.load(json_file) 我遇到的问题是,有时在尝试读取该文件时,该文件正在被更新为新内容,这会导致json.decoder.jsondecodecode错误。如何避免这个错误
with open('data.txt','w') as outfile:
json.dump(data,outfile)
然后,我在任何给定时间读取此文件:
with open('data.txt') as json_file:
data = json.load(json_file)
我遇到的问题是,有时在尝试读取该文件时,该文件正在被更新为新内容,这会导致json.decoder.jsondecodecode错误。如何避免这个错误?可能有一种尝试例外情况,即等待文件可读?最简单的方法是捕获JSONDecodeError
try:
with open('data.txt') as json_file:
data = json.load(json_file)
except JSONDecodeError:
time.sleep(10)
with open('data.txt') as json_file:
data = json.load(json_file)
或者你可以试着回答