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

使用Python 3写入JSON文件仅存最新条目,如何存储全部数据?

问题分析与解决

你的程序中logged_times字典仅保留最新8条条目,核心原因是每次启动程序时,number变量都从0开始初始化,而非从已存储的最大条目编号开始。这导致新记录会覆盖原有字典中相同数字键的旧记录,最终看起来只保留了最新的8条(当你重启程序8次后,旧的1-8键会被新的1-8覆盖)。

修复步骤

1. 正确初始化number变量

程序启动时,读取已有的日志条目,获取最大的编号值作为number的初始值,避免覆盖旧记录:

替换原来的number = 0为以下代码:

# 从已存储的日志中获取最大编号,初始化number
if logged_times:
    # JSON加载后键是字符串,需转为整数取最大值
    number = max(map(int, logged_times.keys()))
else:
    number = 0

2. 清理冗余代码

log函数中的logged_times和days两行是无效的冗余代码,可以直接删除。

修复后的完整代码

import json
from datetime import date

# 读取持久化数据,处理文件不存在的情况
try:
    with open("social_media_log.json", "r") as read_file:
        logged_times = json.load(read_file)
except FileNotFoundError:
    logged_times = {}

try:
    with open("social_media_log_DAYS.json", "r") as read_file:
        days = json.load(read_file)
except FileNotFoundError:
    days = []

today = date.today()
print(today)

# 初始化number为已有的最大条目编号
if logged_times:
    number = max(map(int, logged_times.keys()))
else:
    number = 0

def ask():
    print("What would you like to do?")
    print("L = LOG social media time")
    print("R = get a REPORT of usage")
    print("E = EXIT program")

    response = input().lower()
    
    if response == "l":
        log()
    elif response == "r":
        report()
    elif response == "e":
        return
    else:
        ask() 

def log():
    global number
    number += 1
    print("how long did you use social media just now? # of seconds")
    entry = input() 
    logged_times[str(number)] = {"date" : str(today), "amount" : entry}
    if str(today) not in days:
        days.append(str(today))
    
    # 计算并打印总时长
    amounts = [int(item['amount']) for item in logged_times.values()]
    print(f"total time is {sum(amounts)}")
    
    # 写入持久化文件
    with open("social_media_log.json", "w") as write_file:
        json.dump(logged_times, write_file)
    with open("social_media_log_DAYS.json", "w") as write_file:
        json.dump(days, write_file) 
    ask()

def report():
    # 可补充实现按日期统计等报表功能
    print("Report feature to be implemented.")
    ask()

# 启动程序
ask()

额外优化点

  • 增加文件不存在时的异常处理,避免首次运行报错
  • 将输入命令转为小写,支持大小写不敏感操作
  • 用列表推导式简化总时长计算逻辑
  • 将number转为字符串作为字典键,符合JSON键类型规范(JSON仅支持字符串键)

内容的提问来源于stack exchange,提问作者Sam J. Miller

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 09:25:08