Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 打开文件有时会导致json.decoder.jsondeCoderror_Python_Json - Fatal编程技术网

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)
或者你可以试着回答