Sorting values in a text file in python [duplicate] - python

This question already has answers here:
How to sort a list of strings?
(11 answers)
Closed 3 years ago.
I am developing a game and i need to add a leader board to it. I have coded one which allows the user to add high scores, view high scores and erase all high score. Now I need to sort all the scores in order of highest to lowest. Here's my code currently [NOTE: I'm aware that this isn't the best menu but I will change that later on]:
choice = input(str("Would you like to add a high score to the leader board?: "))
if choice == "y":
user1 = input(str("Enter username 1: "))
hs1 = input(str("Enter high score: "))
user2 = input(str("Enter username 2: "))
hs2 = input(str("Enter high score: "))
data1 = user1 + ": " + hs1
data2 = user2 + ": " + hs2
with open("leaderboard.txt","a") as file:
file.write(data1)
file.write("\n")
file.write(data2)
file.write("\n")
print("Data added.")
elif choice == "n":
final_list = []
with open("leaderboard.txt","r") as file:
first_list = file.readlines()
for i in first_list:
final_list.append(i.strip())
print("Leader board")
print("-------------")
for count in range(0,len(final_list)):
print(final_list[count])
else:
with open("leaderboard.txt","w") as file:
file.write(" ")
print("leader board cleared.")
I would like the leader board to be displayed once ordered something like this:
1. James F: 32
2. Harris W: 18
3. Courtney J: 12
Thank you for reading!

I found that i can restructure how the data is saved to the text file using numerical data first like this:
user1 = input(str("Enter username 1: "))
hs1 = input(str("Enter high score: "))
user2 = input(str("Enter username 2: "))
hs2 = input(str("Enter high score: "))
data1 = hs1 + " - " + user1
data2 = hs2 + " - " + user2
Now the data starts with a number, i can simply use .sort on my list to sort them, however they will be sorted lowest to biggest so i had to use .reverse() to flip the list around.

Related

Writing a program and need some input

I am doing a program about creating a file about golf, it allows only one For. When I run the program I get an error about Golf_File.write(Name + ("\n") ValueError: I/O operation on closed file.
Num_People = int(input("How many golfers are playing?: "))
Golf_File = open('golf.txt', 'w')
for count in range(1,Num_People+1):
Name = input("Enter the player's name: ")
Score = int(input("Enter the player's score: "))
Golf_File.write(Name + ("\n"))
Golf_File.write(str(Score) + ("\n"))
Golf_File.close()
The following will work:
Num_People = int(input("How many golfers are playing?: "))
Golf_File = open('golf.txt', 'w')
for count in range(1,Num_People+1):
Name = input("Enter the player's name: ")
Score = int(input("Enter the player's score: "))
Golf_File.write(Name + ("\n"))
Golf_File.write(str(Score) + ("\n"))
Golf_File.close()
The file should be closed outside the for loop
It is generally considered better to use with statements to handle file objects
Num_People = int(input("How many golfers are playing?: "))
with open('golf.txt', 'w') as Golf_File:
for count in range(1,Num_People+1):
Name = input("Enter the player's name: ")
Score = int(input("Enter the player's score: "))
Golf_File.write(Name + ("\n"))
Golf_File.write(str(Score) + ("\n"))
You can read more about this in the Python documentation about reading and writing files
Also obligatory reminder about the official Python naming standards, capitalized variable names should be avoided

How do i print certain items in a list based on user input in python?

So far the user is supposed to enter their name account number and balance which gets put into list. then I ask for them to input their account number and im supposed to print out their specific number from the list instead of the whole list but cant get it to work.
customers = list()
acctnum = list()
balance= list()
count = 0
while count != 2:
name = input("Enter your name: ")
customers.append(name)
num = int(input("Enter account number: "))
acctnum.append(num)
bal = input("Enter Current Balance:$ ")
print()
balance.append(bal)
count = count + 1
print(customers)
print(acctnum)
print(balance)
personal = int(input("Enter account number: "))
print(personal)
if personal in acctnum:
print(acctnum)
I find dictionaries are useful in applications like this:
accounts = {}
for x in range(2):
name = input("Enter your name: ")
num = int(input("Enter account number: "))
bal = input("Enter Current Balance: $")
accounts[num] = {"name": name, "balance": bal}
print()
for k, v in accounts.items():
print(v["name"] + "'s account " + str(k) + " has $" + v["balance"])
personal = int(input("Enter account number: "))
if personal in accounts:
print("Hello, " + accounts[personal]["name"] + " you have $" + accounts[personal]["balance"])
The data right now is stored in independent lists. You would have to implement using an associative data type such as dictionaries (that are implemented in Python).

Average of marks for three topics

I am trying to create a program that will ask the user for a username and password. If the login details are correct, the program should ask for the students name and then ask for three scores, one for each topic. The program should ask the user if they wish to enter another students details. The program should output the average score for each topic. I cannot work out how to enter the student marks for each topic per student and also how to work out the average for each topic for the class.
Can you please help?
login="teacher"
password="school"
usrnm=input("Please enter your username: ")
pw=input("Please enter your password: ")
if (usrnm==login) and (pw==password):
print("==Welcome to the Mathematics Score Entry Program==")
print("Do you want to enter the students score? Yes/No: ")
option = input()
option = option.title()
student_info = {}
student_data = ['Topic 1 : ', 'Topic 2 : ', 'Topic 3 : ']
while (option != "No"):
student_name = input("Name: ")
student_info[student_name] = {}
score1 = int(input("Please enter the score for topic 1: "))
student_info[student_name][Topic_1] = score1
score2 = int(input("Please enter the score for topic 2: "))
student_info[student_name][Topic_2] = score2
score3 = int(input("Please enter the score for topic 3: "))
student_info[student_name][Topic_3] = score3
print("Do you want to enter the students score? Yes/No: ")
option = input()
option = option.title()
average = sum(student_info.values())/len(student_info)
average = round(average,2)
print ("The average score is ", average)
else:
print("Access denied!")
just keep the marks seperate from the student names
students = []
marks = []
option = ""
while (option != "No"):
students.append(input("Name"))
marks.append([float(input("Mark_Category1:")),
float(input("Mark_Category2:")),
float(input("Mark_Category3:"))])
option = input("Add Another?")
import numpy
print(numpy.average(marks,0))
if you really want to do it without numpy
averages = [sum(a)/float(len(a)) for a in zip(*marks)] # transpose our marks and average each column

PYTHON Sorting dictionary from a text file [duplicate]

This question already has answers here:
How do I sort a dictionary by value?
(34 answers)
Closed 6 years ago.
I am trying to sort a dictionary, "Highest" and "Average" from highest to lowest, but I can not get the dictionary to sort from the text file. I am not sure if I should be using an array instead or if there is a way around it?
This is my code:
import random
score = 0
print("Hello and welcome to the maths quiz!")
while True:
position = input("Are you a pupil or a teacher?: ").lower()
if position not in ("teacher","pupil"):
print ("Please enter 'teacher' or 'pupil'!")
continue
else:
break
if position == 'pupil':
your_name = ""
while your_name == "":
your_name = input("Please enter your name:") # asks the user for their name and then stores it in the variable name
class_no = ""
while class_no not in ["1", "2", "3"]:
class_no = input("Please enter your class - 1, 2 or 3:") # Asks the user for an input
score = 0
for _ in range(10):
number1 = random.randint(1, 11)
number2 = random.randint(1, 11)
operator = random.choice("*-+")
question = ("{0} {1} {2}".format(number1,operator,number2))
solution = eval(question)
answer = input(question+" = ")
if answer == str(solution):
score += 1
print("Correct! Your score is, ", score , )
else:
print("Your answer is not correct")
class_no = ("Class " + class_no + ".txt")
print("Congratulations {0}, you have finished your ten questions!".format(your_name))
if score > 5:
print("Your total score is {0} which is over half.".format(score))
else:
print("Better luck next time {0}, your score is {1} which is lower than half".format(your_name, score))
with open(class_no, "a") as Student_Class:
Student_Class.write(your_name)
Student_Class.write(",")
Student_Class.write(str(score))
Student_Class.write("\n")
else:
while True:
Group = input("Which class would you like to view first? 1, 2 or 3?: ")
if Group not in ("1", "2", "3"):
print ("That's not a class!")
continue
else:
break
Group = ("Class " + Group + ".txt")
while True:
teacherAction = input("How would you like to sort the results? 'alphabetical', 'highest' or 'average'?: ").lower() # Asks the user how they would like to sort the data. Converts answer into lower case to compare easily.
if teacherAction not in ("alphabetical","highest","average"):
print ("Make sure you only input one of the three choices!")
continue
else:
break
with open (Group, "r+") as scores:
PupilAnswer = {}
for line in scores:
column = line.rstrip('\n').split(',')
name = column[0]
score = column[1]
score = int(score)
if name not in PupilAnswer:
PupilAnswer[name] = []
PupilAnswer[name].append(score)
if len(PupilAnswer[name]) > 3:
PupilAnswer[name].pop(0)
if teacherAction == 'alphabetical':
for key in sorted(PupilAnswer):
print(key, PupilAnswer[key])
elif teacherAction == 'highest':
highest = {}
for key, value in PupilAnswer.items():
maximum = max(value)
highest[key] = maximum
for key in sorted(highest, key=highest.get, reverse=True):
print (key, highest[key])
else:
for name in sorted(PupilAnswer):
average = []
for key in (PupilAnswer[name]):
average.append(key)
length = len(average)
total = 0
for key in (average):
total = total + (key)
totalAverage = (total)/length
print (name, totalAverage)
print ("Thank you for using the quiz!")
input("Press 'enter' to exit!")
There is no "sorted" in dictionaries. They are a set of key-value items. Un-ordered.
You can use an OrderedDict.

Trying to call read/write functions

I am a beginner programmer learning python in my intro game development class. The current homework assignment is to create a function to read and write files. We have to do it also where we can use user input to find the file directory. The problem I'n currently having is that I can't figure out how to write the function to open and close the files. I'll post my code for any help. Thank you. I am only focused on Option 8 for the time being.
enter = 0
start = 0
Roger = ()
text_file = ()
line = open("read.txt", "r")
def read_file(line):
for line in text_file:
print(line)
return line
def close_file(text_file):
text_file.close()
return close_file
def update_score(scores, person, amount):
for score in scores:
if score[0].lower() == person.lower():
score[1] += amount
return scores
def update_score1(scores, person, amount):
for score in scores:
if score[0].lower() == person.lower():
score[1] -= amount
return scores
def addition(num1):
return num1 + num1
def square(num):
print("I'm in square")
return num * num
def display(message):
"""Display game instuctions"""
print(message)
def instructions():
"""Display game instuctions"""
print("Welcome to the world's greatest game")
def main():
str1 = ["Roger", 3456]
str2 = ["Justin", 2320]
str3 = ["Beth", 1422]
instructions()
scores = [str1, str2, str3]
start = input("Would you like to view the high score options? y/n ")
if start == "y":
print("""\
Hello! Welcome to the high scores!
Here are the current high score leaders!:
""")
print(scores)
print("""\n\
0 - Sort high scores
1 - Add high score
2 - Reverse the order
3 - Remove a score
4 - Square a number
5 - Add 2 numbers together
6 - Add to a score
7 - Subtract from a score
8 - Read a file
9 - Write to a file
""")
option = int(input("Please enter your selection "))
while option < 8:
print(scores)
if option == 0:
scores.sort()
print("These are the scores sorted alphabetically")
print(scores)
option = option = int(input("Please enter your selection"))
elif option == 1:
print(scores)
print("Please enter your name and score; After entering your name, hit the return key and enter your score")
name = input()
score = int(input())
entry = (name,score)
scores.append(entry)
print(scores)
option = option = int(input("Please enter your selection"))
elif option == 2:
print(scores)
scores.reverse()
print("\nHere are the scores reversed")
print(scores)
option = option = int(input("Please enter your selection"))
elif option == 3:
print(scores)
print("Please enter the high score you would like to remove. After typing the name, hit the return key and enter the score")
name1 = input()
score1 = int(input())
remove = (name1,score1)
scores.remove(remove)
print(scores)
option = option = int(input("Please enter your selection"))
elif option == 4:
val = int(input("Give me a number to square"))
sqd = square(val)
print(sqd)
option = option = int(input("Please enter your selection"))
elif option == 5:
val0 = int(input("Give me one number"))
val1 = int(input("Give me another number"))
addi = (val0 + val1)
print(addi)
option = option = int(input("Please enter your selection"))
elif option == 6:
print(scores)
sc0 = input("Please enter player whose score you would like to increase. ")
sc1 = int(input("Please enter the amount would would like to add to their score. "))
scores = update_score(scores, sc0, sc1)
print(scores)
option = option = int(input("Please enter your selection"))
elif option == 7:
sc2 = input("Please enter player whose score you would like to decrease. ")
sc3 = int(input("Please enter the amount you would like to subtract from their score. "))
scores = update_score1(scores, sc2, sc3)
print(scores)
while option <= 8:
if option == 8:
print (line)
text_file.close()
option = option = int(input("Please enter your selection"))
main()
Function to return a file's contents:
def read_file(filename):
return open(filename).read()
To write to a file:
def write_file(filename, toWrite):
file = open(filename, 'w')
file.write(toWrite)
file.close()
Example usage:
stuffInFile = read_file("myfile.txt")
write_file("myfile.txt", "I just wrote this to a file!")

Categories

Resources