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

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

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


当前回答

我更倾向于抑制异常,而不是检查文件的存在,以避免TOCTTOU错误。Matt的回答是一个很好的例子,但我们可以在Python 3下使用contextlib.suppress()稍微简化它:

import contextlib

with contextlib.suppress(FileNotFoundError):
    os.remove(filename)

如果filename是pathlib。Path对象,而不是字符串,我们可以调用它的.unlink()方法,而不是使用os.remove()。根据我的经验,对于文件系统操作,Path对象比字符串更有用。

因为这个答案中的所有内容都是Python 3独有的,所以它提供了另一个升级的理由。

其他回答

另一种了解文件(或多个文件)是否存在并删除它的方法是使用模块glob。

from glob import glob
import os

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

Glob找到所有可以使用*nix通配符选择模式的文件,并循环该列表。

更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来检查文件是否存在。

我更倾向于抑制异常,而不是检查文件的存在,以避免TOCTTOU错误。Matt的回答是一个很好的例子,但我们可以在Python 3下使用contextlib.suppress()稍微简化它:

import contextlib

with contextlib.suppress(FileNotFoundError):
    os.remove(filename)

如果filename是pathlib。Path对象,而不是字符串,我们可以调用它的.unlink()方法,而不是使用os.remove()。根据我的经验,对于文件系统操作,Path对象比字符串更有用。

因为这个答案中的所有内容都是Python 3独有的,所以它提供了另一个升级的理由。

在Python 3.4或更高版本中,Python的方式是:

import os
from contextlib import suppress

with suppress(OSError):
    os.remove(filename)