简体   繁体   中英

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:

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. 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. 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. new_details would be the new score data you've gotten. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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