我想删除文件文件名,如果它存在。这样说合适吗
if os.path.exists(filename):
os.remove(filename)
有没有更好的办法?一条线路?
我想删除文件文件名,如果它存在。这样说合适吗
if os.path.exists(filename):
os.remove(filename)
有没有更好的办法?一条线路?
当前回答
os.path.exists对文件夹和文件都返回True。考虑使用os.path.isfile来检查文件是否存在。
其他回答
像这样的东西?利用短路评估。如果文件不存在,整个条件就不能为真,所以python不会麻烦求第二部分。
os.path.exists("gogogo.php") and os.remove("gogogo.php")
马特的答案适合老的蟒蛇,凯文的答案适合新蟒蛇。
如果你不希望复制silentremove的函数,这个函数将在path.py中作为remove_p公开:
from path import Path
Path(filename).remove_p()
从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()
if os.path.exists(filename): os.remove(filename)
是一行程序。
你们中的许多人可能不同意——可能是考虑到建议使用三元词“丑陋”——但这引出了一个问题:当人们习惯了丑陋的标准时,当他们把不标准的东西称为“丑陋”时,我们是否应该听从他们的意见。
按照Andy Jones回答的精神,一个真正的三元运算怎么样:
os.remove(fn) if os.path.exists(fn) else None