Note that you are not putting :
on the lines of if
and else
and also if path
is a folder os.path.exists()
will return True
and os.remove()
will throw an error.
You can test whether the file exists with os.path.isfile()
, and if there is remove with os.remove
. Ex.:
import os
if os.path.isfile('TM.ext'):
os.remove("TM.txt")
Or you can delete without testing whether the file exists and capture OSError than the module will launch. Ex.:
import os
try:
os.remove("TM.txt")
except OSError:
pass
Repl.it with the working code
Edit
In order to get nothing implicit from where I took the OSError .
At the module documentation os
is specified at the top:
Note :
All functions in this module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type, but are not accepted by the operating system.
Translating:
Note :
All functions in this module launch OSError for invalid or inaccessible file names or paths. .