I want to delete the file filename
if it exists. Is it proper to say
if os.path.exists(filename):
os.remove(filename)
Is there a better way? A one-line way?
python
I want to delete the file filename
if it exists. Is it proper to say
if os.path.exists(filename):
os.remove(filename)
Is there a better way? A one-line way?
Best Answer
A more pythonic way would be:
Although this takes even more lines and looks very ugly, it avoids the unnecessary call to
os.path.exists()
and follows the python convention of overusing exceptions.It may be worthwhile to write a function to do this for you: