Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing to a new file if it doesn't exist, and appending to a file if it does

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 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.

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.

like image 724
Bondenn Avatar asked Dec 06 '13 20:12

Bondenn


People also ask

What happens if we want to write into a file and that file does not exist?

If file does not exist, it creates a new file. This is the default mode. It opens in text mode. This opens in binary mode.

Can you append to a file that doesn't exist?

Append mode adds information to an existing file, placing the pointer at the end. If a file does not exist, append mode creates the file. Note: The key difference between write and append modes is that append does not clear a file's contents. Add the + sign to include the read functionality.

What happens if we open a file for writing and that file does not exist in that location?

When you open a file for writing, if the file does not exist, a new file is created. When you open a file for writing, if the file exists, the existing file is overwritten with the new file.

What is the difference between writing to a file and appending to a file?

The difference between appending and writing is that when you write to a file, you erase whatever was previously there whereas when you append to a file, you simply add the new information to the end of whatever text was already there.


1 Answers

Have you tried mode 'a+'?

with open(filename, 'a+') as f:     f.write(...) 

Note however that f.tell() will return 0 in Python 2.x. See https://bugs.python.org/issue22651 for details.

like image 128
Eric des Courtis Avatar answered Sep 24 '22 10:09

Eric des Courtis