patternpythonMinor
Python High Score Table
Viewed 0 times
tablehighpythonscore
Problem
I need to be able to store results of a game in a file with names and high scores where I will eventually want to review the file and sort it alphabetically, etc. I'm unsure if I have the correct way of storing the results to be able to do this.
class_number = input('Please enter your class number: ')
from datetime import datetime
now = datetime.now()
time = ('%s/%s/%s %s:%s' % (now.day, now.month, now.year, now.hour, now.minute))
userscore = (user_name, ' ', str(total_score),' ', time, ' ')
if(int(class_number) == 1):
with open('class1.txt', 'a') as myFile:
myFile.writelines(userscore)
myFile.close()
elif(int(class_number) == 2):
with open('class2.txt', 'a') as myFile:
myFile.writelines(userscore)
myFile.close()
elif(int(class_number) == 3):
with open('class3.txt', 'a') as myFile:
myFile.writelines(userscore)
myFile.close()Solution
Your date format is unconventional, because the minutes are not zero-padded. You could use
PEP 8 says that you should put
Calling
The three output blocks should be combined into one.
Contrary to its name,
%02d instead of %s, but an even better solution would be to use now.strftime('%d/%m/%Y %H:%M') or '{:%d/%m/%Y %H:%M}'.format(now).PEP 8 says that you should put
import statements at the top, for maintainability.Calling
open() in the context of a with block, as you have done, is good practice, as it means it will be automatically closed when exiting the block. Therefore, you should eliminate the myFile.close() calls.The three output blocks should be combined into one.
from datetime import datetime
now = datetime.now().strftime('%d/%m/%Y %H:%M')
class_number = input('Please enter your class number: ')
if class_number in ['1', '2', '3']:
with open('class{}.txt'.format(class_number), 'a') as f:
f.writelines((user_name, ' ', str(total_score), ' ', now, ' '))Contrary to its name,
writelines() does not actually add line termination characters to the output. If you intend to append multiple records to a file, it would be better to put each record on a separate line. In that case, consider using a csv.writer with delimiter=' ' to output tabular data.import csv
…
if class_number in ['1', '2', '3']:
with open('class{}.txt'.format(class_number), 'a') as f:
writer = csv.writer(f, delimiter=' ')
csv.writerow((user_name, total_score, now))Code Snippets
from datetime import datetime
now = datetime.now().strftime('%d/%m/%Y %H:%M')
class_number = input('Please enter your class number: ')
if class_number in ['1', '2', '3']:
with open('class{}.txt'.format(class_number), 'a') as f:
f.writelines((user_name, ' ', str(total_score), ' ', now, ' '))import csv
…
if class_number in ['1', '2', '3']:
with open('class{}.txt'.format(class_number), 'a') as f:
writer = csv.writer(f, delimiter=' ')
csv.writerow((user_name, total_score, now))Context
StackExchange Code Review Q#113672, answer score: 7
Revisions (0)
No revisions yet.