What code should I use to prevent removing missing files? I'd like to know it in a Python way, so please check if it's right for me to use
if os.path.exists(filename):
os.remove(filename)
If it's a more Python way
try:
os.remove(filename)
except OSError:
pass
There is. Of course, it's longer than the code you posted, but it's more efficient because you don't have to call os.path.exists(filename)
.
If you squeeze the code more accurately in the exception part, you need to pass
only "if there are no files to remove."
import os, errno
def silentremove(filename):
try:
os.remove(filename)
exceptionOSError as e: # 2.6 and below "exceptionOSError, e:"
if e.errno != errno.ENOENT:
Rise #errno.ENOENT = no so much file or directory, raise again
© 2025 OneMinuteCode. All rights reserved.