Python: Delete / Remove Files

Posted on in Categories , , last updated April 11, 2014

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.

Syntax: Python delete file

import os


import os

Examples: How can I delete a file or folder in Python?

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

import os
## if file exists, delete it ##
if os.path.isfile(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:

import os
## get input ##
myfile= raw_input("Enter file name to delete : ")
## try to delete file ##
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 

A note about deleting an entire directory tree in Python using shutil.rmtree()

Use shutil.rmtree() to delete an entire directory tree; path must point to a directory (but not a symbolic link to a directory). The syntax is:

inport shutil
## syntax ##
shutil.rmtree(path[, ignore_errors[, onerror]])

In this example, delete /nas01/nixcraft/oldfiles/ directory and all its files:

import os
import sys
import shutil
# Get dir name
mydir= raw_input("Enter directory name : ")
## Try to remove tree; if failed show an error using try...except on screen
except OSError, e:
	print ("Error: %s - %s." % (e.filename,e.strerror))

Sample outputs:

Enter directory name : /tmp/foobar/
Error: /tmp/foobar/ - No such file or directory.
Enter directory name : /nas01/nixcraft/oldfiles/
Enter directory name : bar.txt
Error: bar.txt - Not a directory.

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin and a trainer for the Linux operating system/Unix shell scripting. He has worked with global clients and in various industries, including IT, education, defense and space research, and the nonprofit sector. Follow him on Twitter, Facebook, Google+.

3 comment

Leave a Comment