如何向已有记录的CSV文件中按需填充代码数据?
解决CSV用户代码的增量更新需求
需求回顾
- 用户输入单个代码后,程序在CSV中查找该用户:
- 若用户已存在:找到该行下一个空的
CODE列填入代码;所有CODE列都有值时,覆盖第一个CODE1列 - 若用户不存在:新增一行记录,日期为当前日期,新代码填入
CODE1
- 若用户已存在:找到该行下一个空的
原代码问题分析
- 混用Pandas和CSV模块,逻辑冗余且易出错
- 强制要求用户输入所有5个代码,不符合“输入单个代码”的核心需求
- 字典中存在重复键(
KEYWORD1出现两次),会导致数据丢失 - 判断用户存在的方式
username in df.values不准确,可能误匹配其他列的内容
优化后的代码
import pandas as pd from datetime import datetime def update_user_code(username, new_code, csv_path=r"C:\test\codes.csv"): # 获取当前日期 entry_date = datetime.now().strftime("%m/%d/%Y") # 定义CSV列名 fields = ["USER", "DATE", "CODE1", "CODE2", "CODE3", "CODE4", "CODE5"] try: # 读取CSV文件,若文件不存在则创建空DataFrame df = pd.read_csv(csv_path, dtype=str) # 确保列名正确,避免文件列缺失 for col in fields: if col not in df.columns: df[col] = "" except FileNotFoundError: # 文件不存在时初始化空DataFrame df = pd.DataFrame(columns=fields) # 检查用户是否存在 user_idx = df[df["USER"] == username].index if len(user_idx) > 0: # 获取用户所在行的CODE列(CODE1到CODE5) code_cols = [f"CODE{i}" for i in range(1,6)] user_row = df.loc[user_idx[0], code_cols] # 找到第一个空值/NaN的位置 empty_pos = user_row[user_row.isna() | (user_row == "")].index if len(empty_pos) > 0: # 填充第一个空的CODE列 df.loc[user_idx[0], empty_pos[0]] = new_code print(f"用户{username}的{empty_pos[0]}已更新为{new_code},日期更新为{entry_date}") else: # 所有CODE列都有值,覆盖CODE1 df.loc[user_idx[0], "CODE1"] = new_code print(f"用户{username}的CODE列已满,已覆盖CODE1为{new_code},日期更新为{entry_date}") # 更新日期 df.loc[user_idx[0], "DATE"] = entry_date else: # 用户不存在,新增一行 new_row = { "USER": username, "DATE": entry_date, "CODE1": new_code, "CODE2": "", "CODE3": "", "CODE4": "", "CODE5": "" } df = pd.concat([df, pd.DataFrame([new_row])], ignore_index=True) print(f"已新增用户{username},CODE1设为{new_code},日期为{entry_date}") # 保存回CSV,避免索引列写入 df.to_csv(csv_path, index=False) # 示例调用 # update_user_code("silverspoon", "8") # update_user_code("goldspoon", "17") # update_user_code("bronzespoon", "99")
代码说明
- 文件处理:自动处理文件不存在的情况,初始化符合格式的空DataFrame
- 用户存在判断:直接通过
USER列精确匹配,避免误判 - 增量更新:只修改需要更新的CODE列,无需输入所有代码
- 边界处理:自动检测空CODE列,满列时覆盖CODE1,同时更新日期
- 数据安全:使用Pandas的原子化写入逻辑,避免文件读写过程中损坏原数据
内容的提问来源于stack exchange,提问作者silentspoonx
相关产品推荐
相关产品推荐

