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

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

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


当前回答

献吻礼:

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

然后:

remove_if_exists("my.file")

其他回答

从Python 3.8开始,使用missing_ok=True和pathlib.Path.unlink (docs here)

from pathlib import Path

my_file = Path("./dir1/dir2/file.txt")

# Python 3.8+
my_file.unlink(missing_ok=True)

# Python 3.7 and earlier
if my_file.exists():
    my_file.unlink()

按照Andy Jones回答的精神,一个真正的三元运算怎么样:

os.remove(fn) if os.path.exists(fn) else None

像这样的东西?利用短路评估。如果文件不存在,整个条件就不能为真,所以python不会麻烦求第二部分。

os.path.exists("gogogo.php") and os.remove("gogogo.php")

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

import os
from contextlib import suppress

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

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

from glob import glob
import os

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

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