Most pythonic way to delete a file which may not exist

后端 未结 13 1198
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.

提交回复
热议问题