最佳答案
我有一个程序,写一个用户的 highscore
到一个文本文件。当用户选择 playername
时,该文件由用户命名。
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.
以下是相关的代码,目前为止还不起作用:
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.