Asked By – Bondenn
I have a program which writes a user’s
highscore to a text file. The file is named by the user when they choose a
If the file with that specific username already exists, then the program should append to the file (so that you can see more than one
highscore). And if a file with that username doesn’t exist (for example, if the user is new), it should create a new file and write to it.
Here’s the relevant, so far not working, code:
try: with open(player): #player is the varible storing the username input with open(player, 'a') as highscore: highscore.write("Username:", player) except IOError: with open(player + ".txt", 'w') as highscore: highscore.write("Username:", player)
The above code creates a new file if it doesn’t exist, and writes to it. If it exists, nothing has been appended when I check the file, and I get no errors.
Now we will see solution for issue: Writing to a new file if it doesn’t exist, and appending to a file if it does
It’s not clear to me exactly where the high-score that you’re interested in is stored, but the code below should be what you need to check if the file exists and append to it if desired. I prefer this method to the “try/except”.
import os player = 'bob' filename = player+'.txt' if os.path.exists(filename): append_write = 'a' # append if already exists else: append_write = 'w' # make a new file if not highscore = open(filename,append_write) highscore.write("Username: " + player + '\n') highscore.close()
This question is answered By – qmorgan
This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0