Unpickle a Python dictionary via a loop? - python

I am very new to Python and what I am trying to achieve is to pickle a dictionary and then use some form of loop (apologies if I have the terminology incorrect!) to print all the scores in the file.
I am using Python 3.3.3 and here is my attempt, the user enters a name and a score which is first saved to a file and then I try to print it. However I am not able to print the scores.
import pickle
# store the scores in a pickled file
def save_scores(player, score):
f = open("high_score.dat", "ab")
d = {player:score}
pickle.dump(d, f)
f.close
# print all the scores from the file
def print_scores():
# this is the part that I can't get to work!
with open("high_score.dat", "r") as f:
try:
for player, score in pickle.load(f):
print("Player: ", player, " scored : ", score)
except EOFError:
pass
f.close
def main():
player_name = input("Enter a name: ")
player_score = input("Enter a score: ")
save_scores(player = player_name, score = player_score)
print_scores()
main()
input("\nPress the Enter key to exit")
I have Google'd and searched Stackoverflow for similar problems but I must be using the wrong terms as I haven't found a solution.
Thanks in advance.

pickle.load(f) will return a dictionary. If you iterate the dictionary, it yields keys, not key-values pairs.
To yield key-value paris, use items() method (use iteritems() method if you use Python 2.x):
for player, score in pickle.load(f).items():
print("Player: ", k, " scored : ", v)
To get multiple dictionaries out, you need to loop:
with open("high_score.dat", "r") as f:
try:
while True:
for player, score in pickle.load(f).items():
# print("Player: ", k, " scored : ", v) # k, v - typo
print("Player: ", player, " scored : ", score)
except EOFError:
pass
BTW, if you use with statement, you don't need to close the file yourself.
# f.close # This line is not necessary. BTW, the function call is missing `()`

pickle.load will return your dictionary ({player:score})
this code:
for player, score in pickle.load(f):
will try to unpack the returned value as a tuple.
Also, since you ignore the exception it will be hard to tell what went wrong.

I've done a few fixes to make your code work under Python 2 (no Python 3 is available, sorry). Several places were changed. Here it is with some notes:
#!/bin/python2
import pickle
# store the scores in a pickled file
def save_scores(player, score):
f = open("high_score.dat", "wb") # "wb" mode instead of "ab" since there is no obvious way to split pickled objects (surely you can make it, but it seems a bit hard subtask for such task)
d = {player:score}
pickle.dump(d, f)
f.close() # f.close is a method; to call it you should write f.close()
# print all the scores from the file
def print_scores():
# this is the part that I can't get to work!
with open("high_score.dat", "rb") as f: # "rb" mode instead of "r" since if you write in binary mode than you should read in binary mode
try:
scores = pickle.load(f)
for player, score in scores.iteritems(): # Iterate through dict like this in Python 2
print("Player: ", player, " scored : ", score) # player instead of k and score instead of v variables
except EOFError:
pass
# f.close -- 1. close is a method so use f.close(); 2. No need to close file as it is already closed after exiting `where` expression.
def main():
player_name = raw_input("Enter a name: ") # raw_input instead of input - Python 2 vs 3 specific
player_score = raw_input("Enter a score: ")
save_scores(player = player_name, score = player_score)
print_scores()
main()
raw_input("\nPress the Enter key to exit")

Related

how do i sort a leader board and show the top 5

i've been trying to make a leader board for the top 5 scores in order to highest to lowest. however i've ran into a problem and unable to solve it.
this is what i have so far:
import time
limit = 5 # you can set out the limit here.
def leaderboard():
scores = []
print ("\n")
print ("⬇ Check out the leaderboard ⬇")
#LEADERBOARD SECTION
for line in open('H_Highscore.txt', 'r'):
if not line:
pass
else:
*name, score = line.split(",")
score = int(float(score)) # clean and convert to int to order the scores using sort()
scores.append((score, name))
sorted_scores = sorted(scores, reverse = True) # this will sort the scores based on the first position of the tuples
for register in sorted_scores[:limit]:
# I will use string formating, take a look at it, it is really usefull.
text = f"%s: %s pts" % (register[1], register[0])
print(text)
l = open ("H_Highscore.txt", "r")
file_contents = l.read()
print(file_contents)
l.close()
ans = input("does your score beat the top 5?(Y/N) ")
if ans == 'y' or ans == "Y" :
user = str(input("Enter a (user)name: "))
file = open ("H_Highscore.txt", "a")
score = str(input("enter you score: "))
file.write("\n")
file.write(user)
file.write(",")
file.write(str(score)) # (int(x)) can not be written
file.write("pts")
file.write("\n")
file.close()
time.sleep(0.5)
leaderboard()
else:
print("unlucky kentucky")
an error comes up: "invalid literal for int() with base 10: '(A number that i type in for the score)pts/n'.
thank you in advance

Creating a lookup function

I want to create a python lookup function for students. I have a tab delimited file with ID and students name. I want to create a lookup program such that entering either a student's name or ID will return name of the student and student ID if a match has been found.
So far I have imported the data successfully. Snippet of data is shared. Having trouble defining a function. I am sharing my code below:
infile = open("D:/work/student_id.txt", "r")
def lookup():
word =raw_input("code to lookup: ")
print ("\n")
n = elements.index(word)
x = elements[n][0]
y = elements[n][0]
if word == x:
print x, ":", y, "\n"
else:
print("That code does not exist")
lookup()
I searched online(stackoverflow-found post by Erik and Alexander, I tried to model my code like theirs but still no help; O'riley books on Python) for help regarding creation of lookup function but they all involved writing the data out. But I found no guidance on creating a lookup function for an imported tab delimited file. I hope this will help others as well. Any advice?
What version of Python are you using?
Python 3 uses input(), not raw_input().
As your file is tab-separated you can use the csv function.
import csv
students = {}
search = input()
found = None
with open('student_id.txt', newline='') as csvfile:
reader = csv.reader(csvfile, delimiter='\t')
for row in reader:
students[row[0]] = row[1]
print(students)
for i in students.keys():
if search == i:
found = search + " " + students[i]
else:
if search == students[i]:
found = i + " " + students[i]
if found == None:
print("Not found")
else:
print(found)

Trying to load and edit a pickled dictionary, getting an EOFError

I'm trying to modify a trivia program found in a book as part of a tutorial; I need to save the name and score of the player using a pickled dictionary. I've already created the dat file using a separate program, to avoid reading from a file that doesn't exist.
This is the code for the trivia program.
#Trivia Challenge
#Trivia game that reads a plain text file
import sys
def open_file(file_name, mode):
"""Open a file"""
try:
the_file = open(file_name, mode)
except IOError as e:
print("Unable to open the file", file_name, "Ending program.\n", e)
input("\n\nPress the enter key to exit.")
sys.exit()
else:
return the_file
def next_line(the_file):
"""Return next line from the trivia file, formatted."""
line = the_file.readline()
line = line.replace("/", "\n")
return line
def next_block(the_file):
"""Return the next block of data from the triva file."""
category = next_line(the_file)
question = next_line(the_file)
answers = []
for i in range(4):
answers.append(next_line(the_file))
correct = next_line(the_file)
if correct:
correct = correct[0]
explanation = next_line(the_file)
value = next_line(the_file)
return category, question, answers, correct, explanation, value
def welcome(title):
"""Welcome the player and get his or her name."""
print("\t\tWelcome to Trivia Challenge!\n")
print("\t\t", title, "\n")
def saving(player_name):
import pickle
f = open("trivia_scores.dat", "rb+")
highscores = pickle.load(f)
if player_name in highscores and score > highscores[player_name]:
highscores[player_name] = score
pickle.dump(highscores, f)
elif player_name not in highscores:
highscores[player_name] = score
pickle.dump(highscores, f)
print("The current high scores are as follows:")
print(highscores)
f.close()
def main():
trivia_file = open_file("trivia.txt", "r")
title = next_line(trivia_file)
welcome(title)
score = 0
#Get the first block
category, question, answers, correct, explanation, value = next_block(trivia_file)
while category:
#Ask a question
print(category)
print(question)
for i in range(4):
print("\t", i + 1, "-", answers[i])
#Get answer
answer = input("What is your answer?: ")
#Check answer
if answer == correct:
print("\nRight!", end=" ")
score += int(value)
else:
print("\nWrong!", end=" ")
print(explanation)
print("Score:", score, "\n\n")
#Get the next block
category, question, answers, correct, explanation, value = next_block(trivia_file)
trivia_file.close()
print("That was the last question!")
print("Your final score is", score)
return score
player_name = input("First, enter your name: ")
main()
saving(player_name)
input("\n\nPress the enter key to exit.")
The eponymous error occurs at this point:
def saving(player_name):
import pickle
f = open("trivia_scores.dat", "rb+")
highscores = pickle.load(f)
When the questions end, the program attempts to run the "saving" module, which (In theory) opens the trivia_scores.dat file, loads the highscores dictionary, checks to see if the player's name is in the dictionary, and if their current score is higher than the one in the file, it overwrites it.
But for some reason, when the program attempts to load the highscores dictionary, instead I get this error message.
EOFError: Ran out of input
I have never seen this error before. From some cursory googling, I got the impression that it has something to do with the program trying to read from an empty file. But that made no sense to me, since I specifically created a dat file using a different program to prevent that from happening: trivia_scores.dat is NOT an empty file. I even read from it with Python Shell to make sure.
What does this error mean, and why won't Python load the dat file?
Context: The book I'm reading from is Python for the Absolute Beginner, by Michael Dawson. This program and the challenge I'm trying to complete come from chapter 7. The program was running fine before I added the saving module.
Probably the original trivia_scores.dat file you wrote got corrupt (maybe you didn't call close() on it?). You should try creating a new file and adding a pre-populated dictionary to this file. Then try reading from this new file.

Find name in file and then replace their score in python

I have written a game and stored the players scores in a file. However I want to make it so that if a person plays more than once their new scores are stored next to their name, and old scores, in a file. Here is the code I have written so far. I appreciate any help! Thanks!
scores = open('scores.txt', 'r+')
scores.write("Name:%s Score:%d---" % (name,score))
scorel = scores.read()
print (scorel)
scores.close()
P.S as you can probably tell I am new to Python!
This is a crude way of accomplishing what you needed. Note that this might get slow for very large files. You'll need to create a blank .txt file called oldscores.txt manually the first time you run this.
def writeScore(name, score):
name = str(name)
score = str(score)
if name in b:
index = b.index(name)
f.seek(0,0)
with open('oldscores.txt', 'a') as f2:
f2.write(a[index])
if index == (len(b)-1):
newscore = a[index].rstrip("\n").split(" ")
newscore[3] = score
a[index] = " ".join(newscore)
else:
newscore = a[index].rstrip("\n").split(" ")
newscore[3] = score + "\n"
a[index] = " ".join(newscore)
for i in a:
f.write(i)
else:
f.write("\nname: {} score: {}".format(name, score))
with open('scores.txt', 'r+') as f:
a = f.readlines()
b = [i.split(" ")[1] for i in a]
writeScore(PLAYERNAME,SCORE) # Enter the name of the player and the score in here.

How do I allow only the latest inputs to be saved - Python

How do I implement a simple code that will only save the student's latest 3 scores? If the test is repeated later, the old score should be replaced.
Thank you.
This is the code that asks the user the questions and saves the results in the txt. files.
import random
import math
import operator as op
correct_answers = 0
def test():
num1 = random.randint(1, 10)
num2 = random.randint(1, 10)
ops = {
'+': op.add,
'-': op.sub,
'*': op.mul,
}
keys = list(ops.keys())
rand_key = random.choice(keys)
operation = ops[rand_key]
correct_result = operation(num1, num2)
print ("What is {} {} {}?".format(num1, rand_key, num2))
user_answer= int(input("Your answer: "))
if user_answer != correct_result:
print ("Incorrect. The right answer is {}".format(correct_result))
return False
else:
print("Correct!")
return True
username = input("What is your name? ")
print("Hi {}! Welcome to the Arithmetic quiz...".format(username))
class_name = input("Are you in class 1, 2 or 3? ")
correct_answers = 0
num_questions = 10
for i in range(num_questions):
if test():
correct_answers +=1
print("{}: You got {}/{} questions correct.".format(
username,
correct_answers,
num_questions,
))
class_name = class_name + ".txt" #creates a txt file called the class that the user entered earlier on in the quiz.
file = open(class_name , 'a') #These few lines open and then write the username and the marks of the student into the txt file.
name = (username)
file.write(str(username + " : " ))
file.write(str(correct_answers))
file.write('\n') #This puts each different entry on a different line.
file.close() #This closes the file once the infrmation has been written.
A much better solution would be to store the data in a different format that made everything easy. For example, if you used a shelve database that mapped each username to a deque of answers, the whole thing would be this simple:
with shelve.open(class_name) as db:
answers = db.get(username, collections.deque(maxlen=3))
answers.append(correct_answers)
db[username] = answers
But if you can't change the data format, and you need to just append new lines to the end of a human-readable text file, then the only want to find out if there are already 3 answers is to read through every line in the file to see how many are already there. For example:
past_answers = []
with open(class_name) as f:
for i, line in enumerate(f):
# rsplit(…,1) instead of split so users who call
# themselves 'I Rock : 99999' can't cheat the system
name, answers = line.rsplit(' : ', 1)
if name == username:
past_answers.append(i)
And if there were 3 past answers, you have to rewrite the file, skipping line #i. This is the really fun part; text files aren't random-access-editable, so the best you can do is either read it all into memory and write it back out, or copy it all to a temporary file and move it over the original. Like this:
excess_answers = set(past_answers[:-2])
if excess_answers:
with open(class_name) as fin, tempfile.NamedTemporaryFile() as fout:
for i, line in enumerate(fin):
if i not in excess_answers:
fout.write(line)
os.replace(fout.name, fin)
That part is untested. And it requires Python 3.3+; if you have an earlier version and are on Mac or Linux you can just use os.rename instead of replace, but if you're on Windows… you need to do some research, because it's ugly and no fun.
And now, you can finally just append the new answer, as you're already doing.

Categories

Resources