首页 > 解决方案 > 我无法在 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'])

标签: pythonjsondictionary

解决方案


你调用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))

推荐阅读