How to Append to a File or Create If Not Exists in Python


Let’s take a look at different methods for creating and appending to a file in Python using functions such as os.path.exists() and open().

1. Checking if a file exists with os.path.exists()

import os

filename = "file.txt"
if not os.path.exists(filename):
    with open(filename, "w") as f:
        f.write("File created!")
else:
    with open(filename, "a") as f:
        f.write("\nAppended to file!")

The os.path.exists() function allows us to check if a file exists before trying to open it.

If the file does not exist, we can create it with the open() function and w mode.

If the file exists, we can append to it with the open() function and a mode.

2. Creating or appending to a file with open() (x and a mode)

filename = "file.txt"
try:
    with open(filename, "x") as f:
        f.write("File created!")
except FileExistsError:
    with open(filename, "a") as f:
        f.write("\nAppended to file!")

Instead of explicitly using an if-else block, we can attempt to create a file using open() with the x mode.

If the file already exists, a FileExistsError exception will be raised. When we catch that exception, we can instead using open() with the a mode to append to the file.

3. Appending to a file with open() (a mode)

filename = "file.txt"
with open(filename, "a") as f:
    f.write("\nAppended to file!")

We can also simply use open() with the a mode to append to the file without checking if it already exists.

If the file does not exist, it’ll be created automatically.