[Python] How to update a CSV file based on certain condition to get the new value only if that...

Discussão em 'Python' iniciado por Stack, Maio 19, 2025.

  1. Stack

    Stack Membro Participativo

    I have been working on this for a couple of hours, I want to update the CSV file only when the new score is higher than the current score. Let's say the first time I played the game, I got a score of 10 and the next time I got a score of 5, I just want to update the 10 only if the new score is higher than 10. But when I tried it is still update the file even when the new score is lower than the current score and I don't want that to happen. Could you look at the code below and give me some int so I can make that work please? This is Just a part of my code, if the entire code will be needed to help me with that please let me know. I was creating the game using OOP concepts.

    from turtle import Turtle
    import csv

    class ScoreBoard:
    def __init__(self):
    self.score = 0
    self.new_score = 0
    self.text_score = Turtle()
    self.text_score.hideturtle()
    self.text_score.penup()
    self.text_score.goto(200, 260)
    self.text_score.color("white")
    self.update_score()

    def update_score(self):
    self.text_score.clear()
    self.text_score.write(f"Score: {self.score}", align="center", font=("Arial", 20, 'normal'))

    def increase_score(self):
    self.score += 1
    self.text_score.clear()
    self.update_score()

    def game_over(self):
    self.highest_score()
    self.text_score.goto(0, 0)
    self.text_score.color("red")
    self.text_score.write(f"Game over!\nYour highest score is: {self.score}", align="center", font=("Arial", 20, "normal"))

    def highest_score(self):
    if self.score > self.new_score:
    self.new_score = self.score
    try:
    with open("score.csv", "w") as file:
    data = file.write(str(self.new_score))
    self.text_score.write(f"Score: {data}", align="center", font=("Arial", 20, 'normal'))
    except FileNotFoundError:
    with open("score.csv", 'w') as file:
    file.write(self.score)
    self.text_score.write(f"Score: {self.score}", align="center", font=("Arial", 20, 'normal'))
    self.text_score.write(f"Score: {self.score}", align="center", font=("Arial", 20, 'normal'))

    Continue reading...

Compartilhe esta Página