Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most pythonic way to delete a file which may not exist

Tags:

python

I want to delete the file filename if it exists. Is it proper to say

if os.path.exists(filename):     os.remove(filename) 

Is there a better way? A one-line way?

like image 791
Scott C Wilson Avatar asked May 31 '12 20:05

Scott C Wilson


People also ask

What will happen if os remove () is used to remove a non existent file?

The os. remove() function can throw an OSError if, A file doesn't exist at the given path. An error message will be thrown, which we have already seen.

How will you handle the error that you encounter while deleting the file in Python?

Make a function called unlink and put it in namespace PHP. @LarsH See the second code block of the accepted answer. It reraises the exception if the exception is anything but a "no such file or directory" error.


2 Answers

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 
like image 56
Matt Avatar answered Sep 26 '22 21:09

Matt


I prefer to suppress an exception rather than checking for the file's existence, to avoid a TOCTTOU bug. Matt's answer is a good example of this, but we can simplify it slightly under Python 3, using contextlib.suppress():

import contextlib  with contextlib.suppress(FileNotFoundError):     os.remove(filename) 

If filename is a pathlib.Path object instead of a string, we can call its .unlink() method instead of using os.remove(). In my experience, Path objects are more useful than strings for filesystem manipulation.

Since everything in this answer is exclusive to Python 3, it provides yet another reason to upgrade.

like image 29
Kevin Avatar answered Sep 26 '22 21:09

Kevin