You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python:向JSON文件中的字典添加新条目时出现重复写入问题求助

Why Your JSON File Ends Up With Two Dictionaries

The issue here is all about the file pointer position when you open the file in r+ mode. Let me break it down simply:

When you use json.load(open_file), the file pointer moves to the end of the original content after reading it. Then when you call json.dump(movie_database, open_file), it writes the updated list starting from that end position—so you end up with the original JSON data followed by the new updated list in the same file. That's why you see two separate dictionary structures instead of one merged, updated version.

Fix 1: Reset the file pointer and truncate before writing

This keeps everything in a single with block. After reading the data, move the pointer back to the start of the file and truncate (erase) the existing content before writing the updated list:

@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)
        # Move pointer to start of file and erase existing content
        open_file.seek(0)
        open_file.truncate()
        json.dump(movie_database, open_file)
    return render_template("search.html")

Fix 2: Read and write in separate with blocks (cleaner approach)

This avoids dealing with file pointers entirely. Read the data, close the file, modify the list, then open the file in write mode (w) to overwrite it completely with the updated data:

@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,}
    
    # Read existing data
    with open("movie_database.json", "r", encoding="UTF-8") as open_file:
        movie_database = json.load(open_file)
    
    # Add new entry
    movie_database.append(new_entry)
    
    # Overwrite file with updated data
    with open("movie_database.json", "w", encoding="UTF-8") as open_file:
        json.dump(movie_database, open_file)
    
    return render_template("search.html")

Bonus: Handle empty files (optional)

If your movie_database.json might be empty or not exist initially, add a check to initialize an empty list:

try:
    with open("movie_database.json", "r", encoding="UTF-8") as open_file:
        movie_database = json.load(open_file)
except (FileNotFoundError, json.JSONDecodeError):
    movie_database = []

内容的提问来源于stack exchange,提问作者R.Fast

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 18:12:44