Jake Kalcher Jake Kalcher - 7 months ago 12
Python Question

Replacing specific data in a csv file

I'm currently in the process of producing a quiz as a competition between me and my friends, and to learn a bit more about programming which I am relatively new to. My program is intended to keep the last 3 results for each user that uses the quiz and replaces the oldest result with the newest. The current stage I have reached is being able to check if the user has their name in the file, and if not writes to the file as normal.

if team == 'Team 1':
path = 'team1scores.csv'

elif team == 'Team 2':
path = 'team2scores.csv'

elif team == 'Team 3':
path = 'team3scores.csv'

else:
print("--Error Defining File Path--")

with open(path, 'rt') as csvfile:
ver_read = csv.reader(csvfile, delimiter =",")
ver_write = csv.writer(csvfile, delimiter =",")
for row in ver_read:
if user in row:
row_data = list(ver_read)
row_len = len(row_data)
if row_len >= 3:
>>> The Problem is here

else:
with open(path, 'a+', newline='') as csvfile:
csvwriter = csv.writer(csvfile, delimiter=',')
csvwriter.writerows(datacsv)


The problem I have with the program is being able to replace the result, say I had the data below in my csv file with 3 inputs already. These need to be kept in two different columns. As I plan to have a sorting feature included.

Jake,5
Jake,7
Jake,2
Max,9
Lee,8


I have experimented several times with the basis of the code above but I am confused once the program reaches the situation of replacing the information. So far I have been able to overwrite the entire file but not specific pieces of data.

Will the ver_write be neccessary in the next steps?

Edit:
I now have an updated version but still have the same problem, This program is adapted from 2ps's answer to fit into my criteria. It still needs to overwrite and needs to print to two different cells for the name and the score. The basis is there for what I need but it won't work.

from collections import OrderedDict
user_data = OrderedDict()
data_to_write = []
with open(path, 'r+') as csvfile:
ver_read = csv.reader(csvfile, delimiter =";")
for x, row in enumerate(ver_read):
if user == row[0]:
user_data[x] = row
else:
data_to_write.append(row)
if len(user_data) > 2:
keys = user_data.keys()[-2:]
for x in keys:
data_to_write.append(user_data[x])
data_to_write.append(datacsv)
with open(path, 'w') as csvfile:
ver_write = csv.writer(csvfile, delimiter=",")
ver_write.writerows(data_to_write)
else:
with open(path, 'a+', newline='') as csvfile:
csvwriter = csv.writer(csvfile, delimiter=',')
csvwriter.writerows(datacsv)


Am I doing something fundamentally wrong here?

2ps 2ps
Answer
from collections import OrderedDict
user_data = OrderedDict() # dict to hold all matching rows for the user, keyed off of line number
data_to_write = []
with open(path, 'r') as csvfile:  # read-write mode for file
    ver_read = csv.reader(csvfile, delimiter =",")
    for x, row in enumerate(ver_read):
        if user == row[0]:
            user_data[x] = row
        else:
            data_to_write.append(row)   # store it for afterwards
    if len(user_data) >= 3:
        keys = user_data.keys()[-2:] # Grab the last two scores in the file
        for x in keys:
            data_to_write.append(user_data[x])
        # Write the contents of the new score here:
        data_to_write.append(. . . . .)
with open(path, 'w') as csvfile:
    # finally write the changes to file
    ver_write = csv.writer(csvfile, delimiter=",")
    ver_write.writerows(data_to_write)