我想删除文件文件名,如果它存在。这样说合适吗
if os.path.exists(filename):
os.remove(filename)
有没有更好的办法?一条线路?
我想删除文件文件名,如果它存在。这样说合适吗
if os.path.exists(filename):
os.remove(filename)
有没有更好的办法?一条线路?
当前回答
像这样的东西?利用短路评估。如果文件不存在,整个条件就不能为真,所以python不会麻烦求第二部分。
os.path.exists("gogogo.php") and os.remove("gogogo.php")
其他回答
献吻礼:
def remove_if_exists(filename):
if os.path.exists(filename):
os.remove(filename)
然后:
remove_if_exists("my.file")
if os.path.exists(filename): os.remove(filename)
是一行程序。
你们中的许多人可能不同意——可能是考虑到建议使用三元词“丑陋”——但这引出了一个问题:当人们习惯了丑陋的标准时,当他们把不标准的东西称为“丑陋”时,我们是否应该听从他们的意见。
从Python 3.3开始,你可以使用FileNotFoundError,它比公认的版本更正确,因为它没有忽略其他可能的错误。
try:
os.remove(filename)
except FileNotFoundError:
pass
按照Andy Jones回答的精神,一个真正的三元运算怎么样:
os.remove(fn) if os.path.exists(fn) else None
更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