![]() |
Edit Json file - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Edit Json file (/thread-25540.html) |
Edit Json file - mcmxl22 - Apr-02-2020 I am trying to add key\value pairs to a Json file. I can write one pair to the file but I can't figure out how to append additional pairs. When I try, it just replaces the current pair. I have tried following this tutorial but I get key errors. import json product_data = "{}" product = input("Enter product name. ") price = input("enter product price. ") new_product = {product:price} load = json.loads(product_data) load.update(new_product) with open("Product.json", "r+") as file: json.dump(load, file)console output: File output:
RE: Edit Json file - bowlofred - Apr-02-2020 On line 9, product_data is empty, so load is also empty. I think you probably intend to load in the previously written data here. You'll need to load from the file there, very similarly to how you write to the file later in lines 13 and 14. |