0

I want to add a new entry in my dictionary but with my code below it overwrites my existing file with the initial dictionary and adds a second dictionary with my new entry. I want to just have one updated dict. My initial dictionary looks like this: Dictionary

This is my code:

@app.route("/add_movie", methods=["POST"])
def add_movie():
    test_title = request.form["title"]
    test_year = request.form["year"]
    new_entry = {"Title": test_title,"Year": test_year,}
    with open("movie_database.json", "r+", encoding="UTF-8") as open_file:
        movie_database = json.load(open_file)
        movie_database.append(new_entry)
        json.dump(movie_database, open_file)
    return render_template("search.html")

Does anybody know what is wrong here?

1 Answer 1

1

I believe it's because you used

with open("movie_database.json", "r+", encoding="UTF-8") as open_file:

instead of

with open("movie_database.json", "a", encoding="UTF-8") as open_file:

opening with "a" means append to file

Sign up to request clarification or add additional context in comments.

6 Comments

Hi Lex, thanks for your answer. Unfortunately then this error message appears: io.UnsupportedOperation: not readable
then you must need a+ instead of a
Then a new error appears: json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0). Probably because of my json file.
Be sure to remember to invoke json.loads() on the contents of the file, as opposed to the file path of that JSON:
json_file_path = "/path/to/example.json" with open(json_file_path, 'r') as j: contents = json.loads(j.read())
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.