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 !
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: