Most pythonic way to delete a file which may not exist

后端 未结 13 1190
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:23

    Another way to know if the file (or files) exists, and to remove it, is using the module glob.

    from glob import glob
    import os
    
    for filename in glob("*.csv"):
        os.remove(filename)
    

    Glob finds all the files that could select the pattern with a *nix wildcard, and loops the list.

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

    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 silentremove, this functionality is exposed in path.py as remove_p:

    from path import Path
    Path(filename).remove_p()
    
    0 讨论(0)
  • 2020-12-02 04:27

    A KISS offering:

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

    And then:

    remove_if_exists("my.file")
    
    0 讨论(0)
  • 2020-12-02 04:28

    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.

    os.path.exists("gogogo.php") and os.remove("gogogo.php")
    
    0 讨论(0)
  • 2020-12-02 04:28

    This is another solution:

    if os.path.isfile(os.path.join(path, filename)):
        os.remove(os.path.join(path, filename))
    
    0 讨论(0)
  • 2020-12-02 04:30
    if os.path.exists(filename): os.remove(filename)
    

    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".

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