Python: Delete / Remove files

by on February 27, 2013 · 3 comments· last updated at February 27, 2013

How do I delete a file called /tmp/foo.txt using Python programming language under MS-Windows or Unix like operating systems?

You can use either remove("/path/to/file") or unlink("/file/path") to remove (delete) the file path.
Tutorial details
DifficultyEasy (rss)
Root privilegesNo
RequirementsPython

Syntax

import os
os.remove("/tmp/foo.txt")

OR

import os
os.unlink("/tmp/foo.txt")

Examples

A better option is to use os.path.isfile("/path/to/file") to check for whether the file exists or not:

 
#!/usr/bin/python
import os
myfile="/tmp/foo.txt"
 
## if file exists, delete it ##
if os.path.isfile(myfile):
        os.remove(myfile)
else:    ## Show an error ##
        print("Error: %s file not found" % myfile)
 

Or use try:...except OSError as follows to detect error while deleting the file:

 
#!/usr/bin/python
import os
 
## get input ##
myfile= raw_input("Enter file name to delete : ")
 
## try to delete file ##
try:
        os.remove(myfile)
except OSError, e:  ## if failed, report it back to the user ##
        print ("Error: %s - %s." % (e.filename,e.strerror))
 

Sample outputs:

Enter file name to delete : demo.txt
Error: demo.txt - No such file or directory.
Enter file name to delete : rrr.txt
Error: rrr.txt - Operation not permitted.
Enter file name to delete : foo.txt 


You should follow me on twitter here or grab rss feed to keep track of new changes.

Featured Articles:

{ 3 comments… read them below or add one }

1 meow March 1, 2013 at 12:36 pm

The best way deleting files within Python is using shutil module, so this article is sorta useless.

Reply

2 meooooow March 5, 2013 at 3:24 pm

TIMTOWTDIBSCINABTE …

Reply

3 meow March 1, 2013 at 12:42 pm

and note that you’d better using “tempfile” module to work with temporary files, it is secure and does more stuff automatically for you.

Reply

Leave a Comment

You can use these HTML tags and attributes for your code and commands: <strong> <em> <ol> <li> <u> <ul> <kbd> <blockquote> <pre> <a href="" title="">

Tagged as: , , ,

Previous Faq:

Next Faq: