open() in Python does not create a file if it doesn't exist

Here is a code snippet that demonstrates how to use the open() function in Python to create a new file if it does not already exist:

file_name = "example.txt"

try:
    # Attempt to open the file for writing
    f = open(file_name, "x")
    f.close()
    print(f"{file_name} created successfully.")
except FileExistsError:
    # If the file already exists, print a message
    print(f"{file_name} already exists.")

Watch a course Python - The Practical Guide

In this example, we first specify the file name as a string, then use a try-except block to attempt to open the file using the open() function with the "x" mode argument. This tells Python to open the file in "exclusive creation" mode, which means that it will create the file if it does not already exist, but raise a FileExistsError if the file already exists. In case the file already exist, it will print the message "example.txt already exists." and if the file doesn't exist, it will be created and the message "example.txt created successfully." will be printed.