Most pythonic way to delete a file which may not exist

后端 未结 13 1199
Happy的楠姐
Happy的楠姐 2020-12-02 03:50

I want to delete the file filename if it exists. Is it proper to say

if os.path.exists(filename):
    os.remove(filename)

Is

13条回答
  •  时光取名叫无心
    2020-12-02 04:09

    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.

提交回复
热议问题