我无法在python中使用json.loads()从文件中加载字典



我正在尝试使用json.loads()从文本文件(file.txt(加载dict,我可以保存dict,但无法获取它。我有两个脚本:一个保存dict;另一个接收dict。接收的脚本会等到它接收到它,但当它接收到时,它会错误

Traceback (most recent call last):
File "C:/Users/User/Desktop/receiver.py", line 9, in <module>
d = json.loads(file.read())
File "C:UsersUserAppDataLocalProgramsPythonPython38-32libjson__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "C:UsersUserAppDataLocalProgramsPythonPython38-32libjsondecoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:UsersUserAppDataLocalProgramsPythonPython38-32libjsondecoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

这是我的完整脚本,如果可以帮助你

接收。PY

import json
d = {}
while True:
with open('file.txt', 'r') as file:
if file.read():
d = json.loads(file.read())  # It errors here
file.close()
print('Data found in this file !')
break
else:
print('No data in this file..')
print(str(d))

发送。PY

import json
import time
d = {
'Hello': {
'Guys': True,
'World': False,
},
}
time.sleep(5)
with open('file.txt', 'w') as file:
file.write(json.dumps(d))
file.close()
print(d['Hello']['Guys'])

您调用file.read()两次,所以第一次读取所有数据,第二次不会产生任何数据。只需将其存储到一个变量:

import json
d = {}
while True:
with open('file.txt', 'r') as file:
data = file.read()
if data:
d = json.loads(data)
# you also don't need to close the file due to the with statement
print('Data found in this file !')
break
else:
print('No data in this file..')
print(str(d))

添加到Aplet上面的答案中,您可以file.seek(0)在读取文件后将文件对象位置重置为文件的开头:

import json
d = {}
while True:
with open('file.txt', 'r') as file:
if file.read():
file.seek(0)
d = json.loads(file.read())  # It errors here
file.close()
print('Data found in this file !')
break
else:
print('No data in this file..')
print(str(d))

Aplet的答案可能是更好的方法,但这也是一种可能的方法。

有关更多信息,请参阅文档:https://docs.python.org/3/tutorial/inputoutput.html

最新更新