W
W
weranda2021-08-10 20:08:09
Python
weranda, 2021-08-10 20:08:09

How to read data from json file and write it to the same file?

Greetings.
There is a json file. It is necessary to read the data in it, add new ones and write to the same file. I can do all this separately, but I can't do it within one structure with open(file). Please share your solution.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
soremix, 2021-08-10
@weranda

First read, add the necessary data to the object and write. The code will "stretch" into two lines, but it will be clear what is happening.

for extreme sportsmen

with open('file.txt', 'r+') as f:
    data = json.load(f)
    data.append(4)
    f.seek(0)
    json.dump(data, f)

The crutch is shorter than the beautiful and correct code by a whole 1 line

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question