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

如何实现每次运行时自动切换学生代码写入的单元格以避免覆盖

解决学生代码写入表格时覆盖内容的问题

原代码每次运行都会将生成的学生代码固定写入A3单元格,导致旧内容被覆盖。要实现自动切换写入单元格,同时解决跨运行无法检测重复代码的问题,可按以下方式修改:

核心修改点

  • 动态计算下一个空行的单元格地址,避免固定写A3
  • 将users列表持久化到本地文件,确保重启程序后仍能检测重复代码

修改后的完整代码

import os

# 从本地文件读取已存在的学生代码,避免重启后丢失记录
users_file = "existing_users.txt"
users = []
if os.path.exists(users_file):
    with open(users_file, "r") as f:
        users = [line.strip() for line in f.readlines()]

firstname = input("what is your first name:")
lastname = input("what is your last name:")
year = input("what year did you join the school:")
initial = firstname[0:1]

code = year + lastname + initial
# 检测重复代码,重复则添加#后缀
while code in users:
    print(f"This username already exists: {code}")
    code += "#"

print("-"*30)
print(f"your student code is: {code}")
print("-"*30)
users.append(code)

# 将更新后的学生代码列表保存回文件
with open(users_file, "w") as f:
    f.write("\n".join(users))

# 动态获取下一个空行的单元格地址
# 获取表格所有已有的数据行,下一行就是len(rows)+1
rows = sheet.get_values()
next_row = len(rows) + 1
# 构造单元格地址,比如A4、A5...
target_cell = f"A{next_row}"
sheet.update(target_cell, code)

说明

  1. 持久化用户列表:通过本地文件existing_users.txt保存已生成的学生代码,每次运行先读取,结束后写入,解决了原代码重启后users列表为空的问题,能正确检测跨运行的重复代码。
  2. 动态计算单元格:通过sheet.get_values()获取表格中所有已存在的数据行,下一个空行的行号就是总行数+1,以此构造目标单元格地址,实现自动向下写入,不会覆盖旧内容。
  3. 优化重复检测逻辑:把原有的for循环改成while循环,更高效地处理多次重复的情况(比如同一代码重复多次生成时,会自动添加多个#)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 03:40:04