Python's CSV File's Data is Lost Every Run

Question: I’m a high school student currently enrolled in Computer Science foundations course. I’m designing a dating game. I designed an Achieve System that players will achieve while they play their game. However, the CSV file’s data is lost every time when the game is run again.

The achievement system is on Line 265, the first achievement is gained on line 407.

Please help, teacher was not assistant to anyone for project. We have the internet and social media to get help and research,

Repl link:

class Achieve_System:
  def __init__(self, MLR, FLR):
      self.MLR = MLR
      self.FLR = FLR
      self.achieve_file = "achieve_system.csv"

  def achieve_system(self, achievement):
      # Read existing achievements from the file
      with open(self.achieve_file, "r") as achieve_system:
          achieve_reader = csv.reader(achieve_system)
          achieve_rows = list(achieve_reader)

      if achievement in achieve_rows:
          # Open the file in append mode to write new achievement
          with open(self.achieve_file, "a", newline='') as achieve_system:
              achieve_writer = csv.writer(achieve_system)
              print(colored(f"Ta~Da~!, Achieves Earned: {achievement}", "green"))

in line 216 to 223

play_history = open("player_play_history.csv","w")  # create player play history file
play_history.write("FLR,MLR,Current Time,Current Date,Anger level\n")  # headings
playhis_df = pd.read_csv("player_play_history.csv")  # player play history panda dataframe

achieve_system_file = open("achieve_system.csv", "w")  # achieve system file

they are not in any conditions nor nest, therefore they will be executed unless the program ended before that line (which there is no program ending lines before it, so this will run everytime)

on line 216 and 221, you opened the csv of the only 2 csv files, in write mode (“w”), it is different from append mode as you know (I assumed it because you used append mode too) and it clears the data of the file before continuing, this results in file content being cleared and rewritten.

I didnt check any code later than line 223, therefore I cannot ensure there are no more codes that does the same thing later on, please check on your own.
I’m literally ignoring so many optimisation problems lol

Thank you, I got what you mean. I only learn Python for half years, thats the best I could do lol


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.