jdmonroe29 jdmonroe29 - 3 months ago 27
Python Question

Writing Dictionary to .csv

After looking around for about a week, I have been unable to find an answer that I can get to work. I am making an assignment manager for a project for my first year CS class. Everything else works how I'd like it to (no GUI, just text) except that I cannot save data to use each time you reopen it. Basically, I would like to save my classes dictionary:

classes = {period_1:assignment_1, period_2:assignment_2, period_3:assignment_3, period_4:assignment_4, period_5:assignment_5, period_6:assignment_6, period_7:assignment_7}

after the program closes so that I can retain the data stored in the dictionary. However, I cannot get anything I have found to work. Again, this is a beginner CS class, so I don't need anything fancy, just something basic that will work. I am using a school-licensed form of Canopy for the purposes of the class.


Either use the csv library, or do something simple like:

with open("assignments.csv", "w") as f:
    for key, value in classes.items():
        f.write(key + "," + value + "\n")

Edit: Since it seems that you can't read or write files in your system, here's an alternative solution (with pickle and base85):

import pickle, base64

def save(something):
    pklobj = pickle.dumps(something)

def load():
    pklobj = base64.b85decode(input("> ").encode('utf-8'))
    return pickle.loads(pklobj)

To save something, you call save on your object, and copy the string that is printed to your clipboard, then you can save it in a file, for instance.

>>> save(classes)  # in my case: {34: ['foo#', 3]}

To load, you call load() and enter the string:

>>> load()
> fCGJT081iWaRDe;1ONa4W^ZpJaRN&NWpge
{34: ['foo#', 3]}