Skip to content Skip to sidebar Skip to footer

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 i

Solution 1:

As far as I know, you cannot change one row in a file. So you'll have to rewrite the complete file.

I do not know how you insert new data, but you could do the following:

import csv

# Assuming new score
new_score = ['Jake', '3']

# Open the file containing the scoreswithopen('scores.csv', 'r') as csvfile:
    ver_read = csv.reader(csvfile, delimiter=',')

    # Make a dict that will contain the scores per person        
    names = {}
    for row in ver_read:
        # Grab the name and the score
        name,score = list(row)

        # If it's not in names yet, put it in and make it a listif name notin names:
            names[name] = []

        # Append the score to the name list
        names[name].append(score)

# Add the new score
names[new_score[0]].append(new_score[1])

withopen('scores.csv', 'w') as csvfile:
    # Loop the names in the names dictfor name in names:

        # If the person has more than 3 scores, only take the last 3iflen(names[name]) > 3:
            names[name] = names[name][-3:]

        # For each score, print itfor score in names[name]:
            print('{},{}'.format(name, score))
            #ver_write.writerow([name, score])

In:

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

New score:

Jake,3

Out:

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

Solution 2:

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

Solution 3:

You could try something like this maybe:

data_to_write = []
withopen(path, 'r+') as csvfile:  # read-write mode for file
    ver_read = csv.reader(csvfile, delimiter =",")
    row_data = list(ver_read)

    for row in row_data:
        if user in row:
            if row_data.index(row) >= 3:    # if we found the user in a row after 3
                row = []    # change the information here to whatever suits youelse:
                row = []    # or here depending on your logic
        data_to_write.append(row)   # store it for afterwards# finally write the changes to file
    ver_write = csv.writer(csvfile, delimiter=",")
    ver_write.writerows(data_to_write)

Post a Comment for "Replacing Specific Data In A Csv File"