python - 我无法在 python 中使用 json.loads() 从文件中加载字典
问题描述
我正在尝试使用从文本文件(file.txt)加载字典json.loads()
,我可以保存字典,但无法获取它。我有两个脚本:一个保存字典,一个接收它。接收的脚本会一直等到它接收到,但是当它接收到时,它会出错
Traceback (most recent call last):
File "C:/Users/User/Desktop/receiver.py", line 9, in <module>
d = json.loads(file.read())
File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\json\__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\json\decoder.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))
推荐阅读
- mysql - MYSQL - 删除每个 idnumber 输入早于 x 天的行
- python - If 语句检查 number 是否具有预期的位数
- c - 逐行读取文件到结构
- java - 有没有办法将文件中存在的元素存储到java中对象的数组中
- javascript - 如何将文件添加到 serializeArray
- reactjs - 删除包含用户数据的帐户
- graphql - SSR 和 GraphQL:如果不存在 javascript(SEO 目的),如何避免加载状态?
- macos - 在 Mac 上使用 VS 2019 生成的 docker compose 文件时出现问题
- c# - Blazor 输入掩码
- python - 未找到 Kivy 的模块