I want to delete the file filename
if it exists. Is it proper to say
if os.path.exists(filename):
os.remove(filename)
Is
I prefer to suppress an exception rather than checking for the file's existence, to avoid a TOCTTOU bug. Matt's answer is a good example of this, but we can simplify it slightly under Python 3, using contextlib.suppress():
import contextlib
with contextlib.suppress(FileNotFoundError):
os.remove(filename)
If filename
is a pathlib.Path
object instead of a string, we can call its .unlink() method instead of using os.remove()
. In my experience, Path objects are more useful than strings for filesystem manipulation.
Since everything in this answer is exclusive to Python 3, it provides yet another reason to upgrade.