Most pythonic way to delete a file which may not exist

后端 未结 13 1213
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条回答
  •  猫巷女王i
    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()
    

提交回复
热议问题