Dict 在 json 上没有属性 write()

Dict has no attribute write() on json

AttributeError: 'dict' object has no attribute 'write'

发生在 json.dump(data, config_file, indent=4)

import json


def get_json(path):
    with open(path, 'r') as f:
        return json.load(f)


def write_json(path, data):
    config_file = get_json(path)
    json.dump(data, config_file, indent=4)
    config_file.close()



def lines_to_dict(linesUp):
    lines = []
    for line in linesUp:
        lines.append(line.split(':'))
    return dict(lines)

我不明白为什么会出现这样的错误? 我该如何修改此代码?

回溯:

Traceback (most recent call last):
  File "C:\Users\quent\PycharmProjects\testSpinergie\main.py", line 15, in <module>
    update_config("./ressource/fileconf.json", "./ressource/changes.txt")
  File "C:\Users\quent\PycharmProjects\testSpinergie\main.py", line 10, in update_config
    json_util.write_json(pathConfig, dictUp)
  File "C:\Users\quent\PycharmProjects\testSpinergie\utils\json_util.py", line 11, in write_json
    json.dump(data, config_file, indent=4)
  File "C:\Users\quent\AppData\Local\Programs\Python\Python310\lib\json\__init__.py", line 180, in dump
    fp.write(chunk)
AttributeError: 'dict' object has no attribute 'write'

感谢帮手!

json.dump(data, config_file, indent=4)

此函数 json.dump expects an object as the first argument, and a _io.TextIOWrapper 作为第二个参数。


您传递的是 config_file,这是 get_json() 的结果,returns 是 dict


也许你想要这样的东西:

config_file = open(path, 'w')
json.dump(data, config_file, indent=4)
config_file.close()

或(甚至更好):

with open(path, 'w') as config_file:
    json.dump(data, config_file, indent=4)

为了更好地理解 Python 的 I/O 系统是如何工作的,我建议阅读 .

您需要打开新文件才能写入

示例如下:

import json

def get_json(path):
    with open(path, 'r') as f:
        return json.load(f)

def write_json(path, data):
    with open(path, 'w', encoding='utf-8') as config_file:
        json.dump(data, config_file, indent=4)

if __name__ == '__main__':
    data = get_json('input.json')
    write_json('output.json', data)

看看行:

with open(path, 'w', encoding='utf-8') as config_file: