remove a file if it exists if not create it in python

You can use the os module in Python to check if a file exists or not. If the file exists, you can remove it using os.remove(). If it does not exist, you can create it using a try-except block.

Here's an example code:

main.py
import os

filename = "example.txt"

# checking if the file exists
if os.path.exists(filename):
    os.remove(filename)
    print(f"The file '{filename}' has been removed.")

# creating the file using try-except block
try:
    with open(filename, "w") as f:
        f.write("This is a new file.")
    print(f"The file '{filename}' has been created.")
except Exception as e:
    print(f"Error: {e}")
399 chars
17 lines

In this code, we first define the filename that we want to check or create. We then use the os.path.exists() function to check if the file exists. If it does, we remove it using os.remove() and print a message to show that the file has been removed.

If the file does not exist, we move on to the try block where we use the with statement to open the file in write mode and write some text to it. We then print a message to show that the file has been created.

If there is an error while creating the file, the except block will catch the exception and print an error message to the console.

gistlibby LogSnag