How to Append to a File or Create a file in python if it does not already exist?

Let’s see 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 you to check if a file exists before trying to open it.

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

If the file exists, you can append to it with the open() function with 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 using an if-else block, you can attempt to create a file using open() with the x mode.

If the file already exists, a FileExistsError exception will be raised. When you catch that exception, you 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!")

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

that’s all.


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *