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

从TXT文件读取信息存入字典仅一行生效,如何实现全行列存储?

问题原因

你当前的代码会丢失之前的任务数据,核心原因是字典的键具有唯一性——当同一用户(比如示例里的admin)有多条任务时,每次循环都会用新的任务字典替换tasks[user]原来的值,最终只保留最后一行的任务记录。

修改方案

下面提供两种实用的修改思路,可根据你的业务需求选择:

方案1:按用户分组存储任务(同一用户的任务存为列表)

这种结构适合需要按用户维度查看或管理任务的场景,tasks字典的键是用户名,对应的值是该用户的所有任务列表:

tasks = {}

with open('tasks.txt', 'r', encoding='utf-8') as file:
    for line in file:
        line = line.strip()
        # 跳过空行,避免分割后出现索引错误
        if not line:
            continue
        temp = line.split(", ")
        user = temp[0]
        title = temp[1]
        description = temp[2]
        due_date = temp[3]
        date_assigned = temp[4]
        # 去掉状态字段末尾的换行符
        status = temp[5].strip()
        
        # 若用户未在字典中,先初始化空列表
        if user not in tasks:
            tasks[user] = []
        # 将当前任务添加到用户的任务列表
        tasks[user].append({
            'title': title,
            'description': description,
            'due date': due_date,
            'date assigned': date_assigned,
            'status': status
        })

print(tasks)

方案2:用列表存储所有任务(每条任务包含用户信息)

如果需要遍历所有任务,或者任务没有唯一的用户/标题标识,这种结构更灵活,所有任务统一存在一个列表中:

tasks = []

with open('tasks.txt', 'r', encoding='utf-8') as file:
    for line in file:
        line = line.strip()
        if not line:
            continue
        temp = line.split(", ")
        # 构建包含用户信息的任务字典,添加到列表
        tasks.append({
            'user': temp[0],
            'title': temp[1],
            'description': temp[2],
            'due date': temp[3],
            'date assigned': temp[4],
            'status': temp[5].strip()
        })

print(tasks)
额外优化说明
  • 增加了line.strip()和空行判断,避免处理文件中的空白行时触发索引越界错误
  • 对status字段做了strip()处理,去掉末尾可能残留的换行符,保证数据整洁

内容的提问来源于stack exchange,提问作者theramannoodle

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 05:16:07