使用 Python 在 CSV 文件中的特定行中追加/更新数据



好的 我有一个程序,通过使用代码将用户的名字、姓氏和分数输出到字符串(逗号分隔):

result=','.join((strFirstName,strLastName,str(score),"n"))

然后,我可以使用代码将其写入CSV文件:

file=open("filename.csv","a")
    file.write(result)
    file.close()

这工作正常,但是我希望能够为每个用户记录最多 3 个分数,而它只保存他们最新的三个分数。我无法弄清楚如何实现

  1. 仅当用户尚不存在时才写入新行
  2. 使用现有用户
  3. 的最新分数更新现有用户,仅替换最早的分数

就像提到的评论一样,您必须使用字典或列表来跟踪csv文件中的用户,然后修改该字典/列表,然后写回csv。下面是该概念的快速实现:

new_details = dict()
new_details["jack jackson"] = 100
users = dict()
with open("filename.csv", "r") as csv_file:
    for line in csv_file:
        line = line.strip().split(",")
        users[line[0]+" "+line[1]] = line[2:]
with open("filename.csv", "w") as csv_file:
    for user in users:
        user_details = user.split()
        if (user in new_details):
            if len(users[user]) >= 3:
                user_details += users[user][1:] + [str(new_details[user])]
            else:
                user_details += users[user] + [str(new_details[user])]
        else:
            user_details += users[user]
        csv_file.write(','.join(user_details) + "n")
    for user in new_details:
        if user not in users:
            user_details = user.split() + [str(new_details[user])]
            csv_file.write(','.join(user_details)+"n")

一切都基于使用"名字姓氏"键方案的字典。 new_details将是你得到的新分数数据。它将首先将所有现有用户写入 csv(如果存在,则添加新分数),然后再将新用户写入 csv。

最新更新