How can I delete a file if exists in a directory with python 2.7 using os / app
?
I've tried with
os.remove('directory/file.png')
but if the item doesn't exist, I've got an error.
if os.path.exists(path):
os.remove(path)
try:
os.remove(path)
except OSError:
pass
Just catch the error and ignore it. (Ignoring errors isn't something you'd do for all errors, but here, it's what you want.)
Any approach based on checking the file's existence in advance would be prone to race conditions. To avoid race conditions, the existence check has to be part of the removal operation, and this is how you do that in Python.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With