Skip to content Skip to sidebar Skip to footer

Trying To Input A Integer Into A File And Retrieving It As One. Python 3x

so I've been trying to learn Python and I have this little app to conduct an English test. But I want to take the 'score' and put it into a file but not as a string but as an integ

Solution 1:

It's likely easiest to just write it as a string and then read it back as a string:

file = open(filename, 'w')
file.write(str(score))

Later:

score = int(file.read())

However, if there's a reason you want to write it in binary (say to obfuscate the score a bit) there are many options. While it's definitely possible to say, write it using standard integer encoding, I typically just go with the pickle module if I want to serialize data:

import pickle

file = open(filename, "w")
pickle.dump(score, file)
file.close()

Later:

file = open(filename)
score = pickle.load(file)

I like this approach because it works for serializing any kind of data, not just integers. See this post for some leads on writing or reading in full binary, if that's what you truly seek:

Reading a binary file with python

Finally, since you asked for other feedback: if I were implementing this and I wasn't expecting a huge data set, I would just store all of the scores in a dictionary, then pickle and unpickle that dictionary to a single file as necessary.

Solution 2:

If you want to persist the data, using a dict and pickling would be a good approach, you can use a single file and use the name to lookup the user, like your own approach though you will have problems if two users have the same name so you might want to think of how you would make each user choose a uniqe identifier:

questions = ["1. You won't find Jerry at home right now. He ______________ (study) in the library.",
             "2. Samantha ______________   (do) her homework at the moment.",
             "3. We______________  (play) Monopoly a lot.",
             "4. Ouch! I ______________ (cut, just) my finger!",
             "5. Sam (arrive) ______________in San Diego a week ago."]
keys = ["is studying",
        "is doing",
        "play",
        "have just cut",
        "arrived"]

import pickle


defask(scores):
    print("Type in the verb given in brackets in the correct form.\n")
    # this loop asks questions and determines whether the answer is right# if new user default score to 0
    score = scores.get(name, 0)

    # zip the questions and answer togetherfor q, a inzip(questions, keys):
        print("Your current score is: %d" % score)
        answer = input(q)
        if answer == a:
            print("You are right! You get one point")
            score += 1else:
            print("Wrong! You lose one point!")
            # don't want minus scores.if score > 0:
                score -= 1# update or create user name/score pairing and dump to file
    scores[name] = score
    withopen("score.pkl", "wb") as f:
        pickle.dump(scores, f)


# creates a file with the person's nameprint("Hello. This is an English test.")
name = input("What is your name?")


try:
   # first run file won't exist withopen("score.pkl", "rb") as f:
        scores = pickle.load(f)
except IOError as e:
    print(e)
    scores = {}

ask(scores)

Post a Comment for "Trying To Input A Integer Into A File And Retrieving It As One. Python 3x"