I want to delete the file filename
if it exists. Is it proper to say
if os.path.exists(filename):
os.remove(filename)
Is
Another way to know if the file (or files) exists, and to remove it, is using the module glob.
from glob import glob
import os
for filename in glob("*.csv"):
os.remove(filename)
Glob finds all the files that could select the pattern with a *nix wildcard, and loops the list.
Matt's answer is the right one for older Pythons and Kevin's the right answer for newer ones.
If you wish not to copy the function for silentremove
, this functionality is exposed in path.py as remove_p:
from path import Path
Path(filename).remove_p()
A KISS offering:
def remove_if_exists(filename):
if os.path.exists(filename):
os.remove(filename)
And then:
remove_if_exists("my.file")
Something like this? Takes advantage of short-circuit evaluation. If the file does not exist, the whole conditional cannot be true, so python will not bother evaluation the second part.
os.path.exists("gogogo.php") and os.remove("gogogo.php")
This is another solution:
if os.path.isfile(os.path.join(path, filename)):
os.remove(os.path.join(path, filename))
if os.path.exists(filename): os.remove(filename)
is a one-liner.
Many of you may disagree - possibly for reasons like considering the proposed use of ternaries "ugly" - but this begs the question of whether we should listen to people used to ugly standards when they call something non-standard "ugly".