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?
Join Stack Overflow to learn, share knowledge, and build your career.
|
I want to delete the file
Is there a better way? A one-line way? |
|||||||||||||||||||||
|
|
A more pythonic way would be:
Although this takes even more lines and looks very ugly, it avoids the unnecessary call to It may be worthwhile to write a function to do this for you:
|
|||||||||||||||||||||
|
|
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
If Since everything in this answer is exclusive to Python 3, it provides yet another reason to upgrade. |
|||||||||||||||||||||
|
|
|
||||
|
|
|
In the spirit of Andy Jones' answer, how about an authentic ternary operation:
|
|||||||||||||||||||||
|
|
Another way to know if the file (or files) exists, and to remove it, is using the module glob.
Glob finds all the files that could select the pattern with a *nix wildcard, and loops the list. |
|||||
|
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". |
|||||||||
|
|
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.
|
|||||||||||||
|
|
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
|
|||
|
|
|
I would just use shutil
|
|||||
|
|
os.remove is supposed to work fine:
|
|||
|
|