1

I have created a quiz game in Python that also contains a login and register program however I'm trying to add a scoring system.

Currently, I have the CSV file set out like this:

username,password,score

When you create an account the score is set to 0 and is loaded when you log in using:

for row in users:
     if username == row[0]:
         currentScore = row[2]
         currentScore = int((currentScore))

This grabs the users high score from the CSV file. However when a game finishes I have this setup to determine if their new score is higher than there old score or not:

if int(score) > int(currentScore):
    currentscore = score

I then need it to open the database and find the user that is playing and update there score with the new one. How would I do this? I have tried to get csv to edit a certain row but it doesn't seem to work.

Full code can be found here:https://pastebin.com/q07qazJA

4
  • 1
    then need it to open the database, and which database would that be? a csv isn't a database, why not just use sqlite since it comes in the standard lib. will make your life a whole lot easier. Commented Jan 25, 2019 at 1:07
  • I you don't want to deal with sql use a .json file. You can treat the data as a dict instead of needing to loop through all the data. A dict is hashed allowing for easier lookups, otherwise I'd suggest using pandas to make your life easier with the csv file. Commented Jan 25, 2019 at 1:31
  • Why don't you use pandas for this? It's really an awesome package. Commented Jan 25, 2019 at 2:36
  • Pandas is a really awesome package, but it comes with a high overhead. Using it only to read/write a csv file is unsane on a efficiency point of view. Remember that sentence: if your only tool is a hammer, every problem looks like a nail Commented Jan 25, 2019 at 10:32

1 Answer 1

1

TL;DR

if int(score) > int(currentScore):
    currentscore = score

    r = csv.reader(open('users.csv'))
    lines = list(r)
    for n, line in enumerate(lines):
        if [username, password] == list(line):
            break
    lines[n] = username, password, score

    writer = csv.writer(open('users.csv', 'w'))
    writer.writerows(lines)

quiz = False

Explanation: Editing a row will need to be done in two steps since it's not practical to read and write to the same line of the file, so first open the csv file, read and save the data it to a list, edit the list, then open the file again to write the edited list back to the csv.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.