我想删除文件文件名,如果它存在。这样说合适吗

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

有没有更好的办法?一条线路?


当前回答

这是另一个解决方案:

if os.path.isfile(os.path.join(path, filename)):
    os.remove(os.path.join(path, filename))

其他回答

马特的答案适合老的蟒蛇,凯文的答案适合新蟒蛇。

如果你不希望复制silentremove的函数,这个函数将在path.py中作为remove_p公开:

from path import Path
Path(filename).remove_p()

这是另一个解决方案:

if os.path.isfile(os.path.join(path, filename)):
    os.remove(os.path.join(path, filename))

更python化的方式是:

try:
    os.remove(filename)
except OSError:
    pass

尽管这需要更多的行,而且看起来很丑,但它避免了对os.path.exists()的不必要调用,并遵循了过度使用异常的python约定。

为你写一个函数来做这件事可能是值得的:

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

os.path.exists对文件夹和文件都返回True。考虑使用os.path.isfile来检查文件是否存在。

献吻礼:

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

然后:

remove_if_exists("my.file")