简体   繁体   English

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

[英]Append/Update data in a specific row in a CSV file using Python

OK I have a program that outputs a users First name, Lastname and score to a string (comma separated) by using the code: 好的,我有一个程序可以使用以下代码输出用户的名字,姓氏和分数(以逗号分隔):

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

I can then write this to a CSV file using the code: 然后,我可以使用以下代码将其写入CSV文件:

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

This works fine however I want to be able to record a maximum of 3 scores for each user where it only saves their latest three scores. 效果很好,但是我希望能够为每个用户最多记录3个分数,而只保存他们最近的3个分数。 I cannot work out how to achieve 我不知道如何实现

  1. Only write a new row if the user does not already exist 仅在用户不存在时写新行
  2. Update an existing user with their latest score replacing the oldest score only 用最新分数更新现有用户,仅替换最早的分数

Like the comment mentioned, you'd have to use a dictionary or list to track users from the csv file, then modify that dictionary/list, then write back to the csv. 就像提到的评论一样,您必须使用字典或列表来从csv文件中跟踪用户,然后修改该字典/列表,然后写回csv。 Here's a quick implementation of that concept: 这是该概念的快速实现:

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")

Everything is based around dictionaries that use a "firstName lastName" key scheme. 一切都基于使用“ firstName lastName”键方案的词典。 new_details would be the new score data you've gotten. new_details将是您获得的新分数数据。 It'll first write all existing users to the csv (adding in the new score if it exists), before writing the new users to the csv. 首先将所有现有用户写入CSV(如果存在新分数,则将其添加),然后再将新用户写入CSV。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM