简体   繁体   中英

I cant get my simple shelve python script to work

Hey guys i am working on a project for school where i have to ask 10 math questions then store their score name and class but the only thing is i cant seem to get the right back to work in shelve. below is the code im trying to get to work any help would be good.

global username
global clss
global score
file = shelve.open('score.txt',writeback=True)
try:
    file['score'] = (username, score, clss)
finally:
    file.close ()

EDIT

The thing I am trying to do is to create a script that saves the score class and age of a person. the error im getting is that every time i run the script it deletes the previous data

EDIT change my code to

    global username
    global clss
    global score
    file = shelve.open('score',writeback=True)
    try:
        if 'scores' not in file.keys():
            file['score'] = [ (username, score, clss) ]
        else:
            file['score'].append( (username, score, clss) )
    finally:
        file.close ()

As I mentioned above, writeback alone will not work if you are just using one tuple. If you want to append a list of user/score/class (ie subject) tuples, then do that. (Make sure to keep writeback set to true or else this direct call to append will not work).

try:
    if 'scores' not in file.keys():
        file['scores'] = [ (username, score, clss) ]
    else:
        file['scores'].append( (username, score, clss) )

Check the Python documentation for "open." https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files

There is a second field, a string (eg "r+"), which changes whether the file is appended to, read-only, or re-written. That should help you.

You may want to bookmark the Python documentation online for more questions of this sort.

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