A more pythonic way would be:
try:
os.remove(filename)
except OSError:
pass
Although this takes even more lines and looks very ugly, it avoids the unnecessary call to os.path.exists()
and follows the python convention of overusing exceptions.
It may be worthwhile to write a function to do this for you:
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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…