Most pythonic way to delete a file which may not exist

后端 未结 13 1189
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:07

    Another solution with your own message in exception.

    import os
    
    try:
        os.remove(filename)
    except:
        print("Not able to delete the file %s" % filename)
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-02 04:12

    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
    
    0 讨论(0)
  • 2020-12-02 04:13

    As of Python 3.8, use missing_ok=True and pathlib.Path.unlink (docs here)

    from pathlib import Path
    
    my_file = Path("./dir1/dir2/file.txt")
    
    # Python 3.8+
    my_file.unlink(missing_ok=True)
    
    # Python 3.7 and earlier
    if my_file.exists():
        my_file.unlink()
    
    0 讨论(0)
  • 2020-12-02 04:19

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

    os.remove(fn) if os.path.exists(fn) else None
    
    0 讨论(0)
  • 2020-12-02 04:20

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

    0 讨论(0)
提交回复
热议问题