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