The Python Oracle

Most pythonic way to delete a file which may not exist

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Magic Ocean Looping

--

Chapters
00:00 Question
00:26 Accepted answer (Score 779)
01:07 Answer 2 (Score 250)
01:51 Answer 3 (Score 97)
02:12 Answer 4 (Score 55)
02:31 Thank you

--

Full question
https://stackoverflow.com/questions/1084...

Answer 1 links:
[TOCTTOU]: http://en.wikipedia.org/wiki/TOCTTOU
[contextlib.suppress()]: https://docs.python.org/3/library/contex...
[.unlink()]: https://docs.python.org/3/library/pathli...

Answer 2 links:
[docs here]: https://docs.python.org/3/library/pathli...

Answer 3 links:
[os.path.exists]: https://docs.python.org/2/library/os.pat...
[os.path.isfile]: https://docs.python.org/2/library/os.pat...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python

#avk47



ACCEPTED ANSWER

Score 823


A more pythonic way would be:

try:
    os.remove(filename)
except OSError:
    pass

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:

import os, errno

def silentremove(filename):
    try:
        os.remove(filename)
    except OSError as e: # this would be "except OSError, e:" before Python 2.6
        if e.errno != errno.ENOENT: # errno.ENOENT = no such file or directory
            raise # re-raise exception if a different error occurred



ANSWER 2

Score 277


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.




ANSWER 3

Score 57


os.path.exists returns True for folders as well as files. Consider using os.path.isfile to check for whether the file exists instead.




ANSWER 4

Score 50


In the spirit of Andy Jones' answer, how about an authentic ternary operation:

os.remove(fn) if os.path.exists(fn) else None