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

It happens on 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)

I dont understand why i have an error like this? How can i modify this code?

TraceBack :

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'

Thanks for helpers !

FLAK-ZOSO
  • 3,873
  • 4
  • 8
  • 28
  • 1
    Could you provide the full traceback? – FLAK-ZOSO Apr 06 '22 at 11:34
  • ``json.dump`` expects a file-like object as second argument - and you're passing in a dict. [See docs](https://docs.python.org/3/library/json.html) – Mike Scotty Apr 06 '22 at 11:35
  • `config_file = get_json(path)` gets a json data which you then try to write *to* by `json.dump(data, config_file, indent=4)` - that is not going to work ever. – luk2302 Apr 06 '22 at 11:35

2 Answers2

2

You need to open new file to write

Here is the example:

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)

Take a look at line:

with open(path, 'w', encoding='utf-8') as config_file:
Alex Kosh
  • 2,206
  • 2
  • 19
  • 18
1
json.dump(data, config_file, indent=4)

This function json.dump expects an object as the first argument, and a _io.TextIOWrapper as the second argument.


You are passing config_file instead, which is the result of get_json(), which returns a dict.


Maybe you wanted something like this:

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

or (even better):

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

To better understand how does Python's I/O system work, I would suggest to read this.

FLAK-ZOSO
  • 3,873
  • 4
  • 8
  • 28