Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete a file if it exists?

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.

like image 823
Tiziano Dan Avatar asked Aug 30 '13 02:08

Tiziano Dan


2 Answers

if os.path.exists(path):
    os.remove(path)
like image 32
mattexx Avatar answered Oct 01 '22 14:10

mattexx


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.

like image 169
user2357112 supports Monica Avatar answered Oct 01 '22 16:10

user2357112 supports Monica