Most pythonic way to delete a file which may not exist

后端 未结 13 1191
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:31

    In Python 3.4 or later version, the pythonic way would be:

    import os
    from contextlib import suppress
    
    with suppress(OSError):
        os.remove(filename)
    
    0 讨论(0)
提交回复
热议问题