当前位置: 首页 > 知识库问答 >
问题:

dict在json上没有属性write()[复制]

万俟浩
2023-03-14
AttributeError: 'dict' object has no attribute 'write'

它发生在json上。转储(数据、配置文件、缩进=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'

谢谢你的帮助!

共有2个答案

微生智刚
2023-03-14
json.dump(data, config_file, indent=4)

这个函数json。dump需要一个对象作为第一个参数,以及一个\u io。TextIOWrapper作为第二个参数。

而是传递config_文件,这是get_json()的结果,它返回一个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系统是如何工作的,我建议阅读这篇

慎俊雄
2023-03-14

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

以下是示例

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:
 类似资料:
  • 问题内容: 错误::’dict’对象没有属性’_meta’ 问题答案: 序列化器将等待普通的查询集,而不是(由返回)。如果只想查询某些字段,请使用

  • 问题:我在运行下面的代码时出错。我是新手,不知道如何解决这个问题。creae函数将每个坐标点指定给其自治区。

  • 我是python新手,找不到这个问题的答案。参考消息末尾的代码,我可以知道下一行中“for item,total in totals.items()”部分是什么意思吗? 此外,代码失败,并表示 AttributeError:“dict”对象没有属性“Predictor” 当我将代码中“item(s)”的所有实例更改为“predictor(s)”时。为什么会这样?

  • 在这个错误之前,它已经给了我另一个“xrange不存在”之类的信息,所以我查找了它,并将nx_shp.py文件中的更改为,这似乎解决了这个问题。 根据我所读到的内容,它可能与Python版本(Python2 vs Python3)有关。

  • 在Python中遍历图形时,我收到了这个错误: “dict”对象没有属性“has\u key” 这是我的密码: 该代码旨在找到从一个节点到其他节点的路径。代码来源:http://cs.mwsu.edu/~terry/courses/4883/lectures/graphs.html 为什么我会出现这个错误?我如何修复它?

  • 我正在尝试在ansible playbook中运行任务,如下所示。 我正在使用macOS,并且已经安装了可扫描和单刀道。我能够通过远程Linux计算机上的ansible运行不同的任务,但是当运行此组任务时,我收到错误,因为。 请指导我可能是什么问题? 编辑:追溯问题 编辑: 我被要求检查<code>ansible。cfg文件。但我无法在mac上找到这个文件。 下面是我使用命令时的日志 2.7.6