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?

share|improve this question
4  
Do you want to try to delete a file if it exists (and fail if you lack permissions) or to do a best-effort delete and never have an error thrown back in your face? – Donal Fellows May 31 '12 at 20:09
1  
The latter. Best effort delete. – Scott C Wilson May 31 '12 at 20:19
2  
@Matt nailed it. Seek forgiveness, not permission. – Scott C Wilson Jun 1 '12 at 19:56
    
I wanted to do "the former" of what @DonalFellows said. For that, I guess Scott's original code would be a good approach? – LarsH Dec 11 '13 at 15:48
1  
@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. – jpmc26 Feb 11 '14 at 20:16

10 Answers 10

up vote 384 down vote accepted

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
share|improve this answer
15  
But would this pass if the remove operation failed (read only file system or some other unexpected issue)? – Scott C Wilson May 31 '12 at 20:12
96  
Also, the fact that the file exists when os.path.exists() is executed does not mean that it exists when os.remove() is executed. – kindall May 31 '12 at 20:12
3  
My +1, but overusing of exceptions is not a Python convention :) Or is it? – pepr May 31 '12 at 20:49
6  
@pepr I was just humorously criticizing how exceptions are part of normal behavior in python. For example, iterators must raise exceptions in order to stop iterating. – Matt May 31 '12 at 21:37
3  
@Matt, exceptions are not errors but just exceptional incidents; so raising one when an iterator cannot continue is just following this logic. – Alfe Sep 4 '12 at 15:24

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.

share|improve this answer
1  
This even cleaner than try/except. – magu_ Jun 15 '15 at 18:06
5  
This is the most pythonic way as on December 2015. Python keeps evolving though. – Mayank Jaiswal Dec 16 '15 at 11:37
1  
I found no remove() method for pathlib.Path objects on Python 3.6 – BrianHVB Mar 1 '16 at 16:31
    
@BrianHVB: Thanks, fixed. – Kevin Mar 1 '16 at 16:43
    
Not in Python 2.* – Evgenii Puchkaryov Mar 23 '17 at 23:20

os.path.exists returns True for folders as well as files. Consider using os.path.isfile to check for whether the file exists instead.

share|improve this answer

In the spirit of Andy Jones' answer, how about an authentic ternary operation:

os.remove(fn) if os.path.exists(fn) else None
share|improve this answer
19  
Ugly misuse of ternaries. – bgusach Sep 10 '15 at 14:15
    
@bgusach Why ugly? – BrianHVB Mar 1 '16 at 16:32
7  
@BrianHVB Because ternaries are there to choose between two values based on a condition, not to do branching. – bgusach Mar 1 '16 at 17:29
    
I've found this very useful in maps and apply's :) – Cedric H. Aug 16 '17 at 7:02
    
I don't like to use exceptions for flow control. They make code difficult to understand and more importantly can mask some other error occurring (like a permission issue blocking a file delete) which will cause a silent fail. – Ed King Oct 24 '17 at 17:06

Another way to know if the file (or files) exists, and to remove it, is using the module glob.

from glob import glob
import os

for filename in glob("*.csv"):
    os.remove(filename)

Glob finds all the files that could select the pattern with a *nix wildcard, and loops the list.

share|improve this answer
    
Thanks for this. Didn't know about the glob module... the wildcard wasn't working otherwise – snd Nov 27 '15 at 4:35
if os.path.exists(filename): os.remove(filename)

is a one-liner.

Many of you may disagree - possibly for reasons like considering the proposed use of ternaries "ugly" - but this begs the question of whether we should listen to people used to ugly standards when they call something non-standard "ugly".

share|improve this answer
    
this is clean -- I don't like to use exceptions for flow control. They make code difficult to understand and more importantly can mask some other error occurring (like a permission issue blocking a file delete) which will cause a silent fail. – Ed King Oct 24 '17 at 17:05
    
It's not pretty because it assumes there is only one process that will modify filename. It's not atomic. It's safe and correct to attempt the operation and fail gracefully. It's annoying that Python can't standardize. If we had a directory, we'd use shutil and it would support exactly what we want. – ConnorWGarvey Dec 28 '17 at 17:14

Something like this? Takes advantage of short-circuit evaluation. If the file does not exist, the whole conditional cannot be true, so python will not bother evaluation the second part.

os.path.exists("gogogo.php") and os.remove("gogogo.php")
share|improve this answer
20  
This is definitely not "more Pythonic"—in fact, it's something Guido specifically warns about, and refers to as "abuse" of the boolean operators. – abarnert May 31 '12 at 21:38
    
oh, I agree - part of the question asked for a one line way and this was the first thing that popped into my head – Andy Jones May 31 '12 at 22:21
4  
Well, you could also make it a one-liner by just removing the newline after the colon… Or, even better, Guide grudgingly added the if-expression to stop people from "abusing the boolean operators", and there's a great opportunity to prove that anything can be abused: os.remove("gogogo.php") if os.path.exists("gogogo.php") else None. :) – abarnert Jun 1 '12 at 19:03

Matt's answer is the right one for older Pythons and Kevin's the right answer for newer ones.

If you wish not to copy the function for silentremove, this functionality is exposed in path.py as remove_p:

from path import Path
Path(filename).remove_p()
share|improve this answer

I would just use shutil

import shutil shutil.rmtree(filename, ignore_errors=True)

share|improve this answer
    
Does not work, results in [Errno 20] Not a directory: 'my.file' for non-directories. with ignore_errors=True you just don't see it. The file will still be there. – frans Nov 20 '17 at 8:41

os.remove is supposed to work fine:

import os
Input = input('File:')
File = Input.get()
try:
  os.remove(File)
except:
  none

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.