Reading from a dictionary in a csv file

Question:

I’m trying to create a piece of code were it asks for your name and score, then saves your most recent scores to a csv file. I have managed to get it to check if you are in the dictionary and store your 3 latest scores in a the csv file. However, I do not know how to get the code to open the file which it is saved in, meaning after every time the dictionary is saved it just has your latest store and deleting everything else.

This is what I have got:

import csv

nam=input("Name")
sco=int(input("Score"))


if nam in class1:
    namsco=class1[nam]
    del class1[nam]
    del namsco[0]
    namsco.append(sco)
    class1[nam]=namsco
    print("Score added")
else:
    print ("Creating profile")
    class1[nam]=[0,0,sco]
    print("Score added")


with open('temp.csv', 'w') as f:
    w = csv.DictWriter(f, class1.keys())
    w.writeheader()
    w.writerow(class1)

I left out class1={} because that would need to be added when the dictionary is imported.

Asked By: user4612158

||

Answers:

You are looking for the ‘a’ argument (appends to the file), instead of ‘w’.

Answered By: Ryan Serra

The following tries to initialize the class1 dictionary with the data in the csv file. If this fails because it’s the first time and the file doesn’t exist, it’s set to an empty dictionary.

Next it updates this dictionary by either adding a new entry or updating an existing one, and then at end rewrites the entire file with the values from the updated dictionary.

Note that when using csv.DictReader and csv.DictWriter, each row is also a dictionary. In this case it might have been easier to use csv.reader and csv.writer where each row is just a sequence of values.

import csv

name = input('Name: ')
score = int(input('Score: '))

try:
    with open('class1.csv', 'r', newline='') as inf:
        class1 = {row['name']: [row['score0'], row['score1'], row['score2']]
                    for row in csv.DictReader(inf)}
except FileNotFoundError:
    class1 = {}

print('Updating' if name in class1 else 'Creating', name+"'s", 'profile')
del class1.setdefault(name, [0, 0, 0])[0]
class1[name].append(score)
print('Score added')

with open('class1.csv', 'w', newline='') as outf:
    FIELD_NAMES = ['name', 'score0', 'score1', 'score2']
    writer = csv.DictWriter(outf, FIELD_NAMES)
    writer.writeheader()
    writer.writerows(dict(zip(FIELD_NAMES, [name] + scores))
                        for name, scores in class1.items())
print('File written')
Answered By: martineau
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.