how to append datas in json file each time the code is running with python?

Viewed 36

hello i try to write in my json file so i do like this :

i got my json file (filed.json):

[
    {"id":12},
    {"id":11},
    {"id":34},
    {"id":19}
]

and my python file is :

import json

arr_of_user_id = [12,11,34,19]

for i in arr_of_user_id
    datas_to_post_every_1_day = {"id": i}

with open('filed.json', 'w') as file:
    json.dump([{'owner_id': id} for id in zip(
        id)], file)

jsonfile = open('filed.json')
data = json.load(jsonfile)
for users in arr_of_user_id: #[12, 11, 34, 19]
    data.append(list_of_user_id)

with open("filed.json", "w") as file:
    json.dump(data, file)

so, when i run my code once i got this :

 [
    {"id":12},
    {"id":11},
    {"id":34},
    {"id":19}
 ]

this is perfect, this is the result i want, but when i run the code a second time i have the same result, I would like that each time I run the code, a new data is inserted in my json file, but it dont work ... it only works on the first code run

small precision, when I write a+ instead of w, it creates an invalid json file of type [{}][{}]

thanks!

1 Answers

It looks like here

for i in list_of_user_id
    datas_to_post_every_1_day = {"id": i}

with open('filed.json', 'w') as file:
    json.dump([{'owner_id': id} for id in zip(
        id)], file)

you're creating the data which is read later in the code. Since the data created here never changes, the data written at the end of your code never changes.

Related