Reputation: 165
I have done a math quiz as practice. Part of Task 3 is to organise a CSV file containing names and scores into alphabetical order. I have done some code, but I would like to know how to make it work like I expect it to. I'm not really sure what I have done, so please can you keep explanations simple.
data = input('How would you like the data? a for alphabetically, b for highest score to lowest and c for average score highest to lowest. press q to exit: ')
if 'a':
score_file = open('scorefile.csv')
for x in sorted (score_file, key=str.lower):
print (x)
This is what it looks like when it is run:
Upvotes: 1
Views: 828
Reputation: 4010
See what's going on here?
>>> if "a":
... print ("True!")
... else:
... print("False!")
...
True!
>>>
>>> if "aadasgabherbasdvc23d3wv":
... print ("True!")
... else:
... print("False!")
...
True!
>>>
>>> if "":
... print ("True!")
... else:
... print("False!")
...
False!
>>>
>>> if None:
... print ("True!")
... else:
... print("False!")
...
False!
>>>
Any non-empty string will evaluate to True
. Empty strings and the keyword None
evaluate to False
(there are probably more examples).
This means that no matter what you enter, the code nested under if 'a'
will be executed. If/when you write the code for user inputs "b" and "c", you'll see this.
If you want to compare user input to the string 'a'
, you'd do:
data = input('How would you like the data? a for alphabetically, b for highest score to lowest and c for average score highest to lowest. press q to exit: ')
if data == 'a':
# do something
Regarding the rest of the code... Python has a csv
module. You can easily split a csv file manually since it should be comma-delimited but the csv
module handles it in a slightly more sophisticated way (I'm not sure but I think it understands values with commas in them, for instance).
When you use open()
, don't forget to call close()
afterwards. You can avoid this open/close
business altogether by using with
(which is called a context manager btw.). You can then do
import csv
with open('scorefile.csv', 'r') as csv_file:
rows = csv.reader(csv_file)
or
with open('scorefile.csv', 'r') as csv_file:
for line in csv_file:
...
or whatever you want to do with the file. The key point is that using with
takes care of closing the file automatically once you're done reading the data. That way, you don't have to remember to call close()
.
Upvotes: 1