Python: Delete / Remove Files

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.
[donotprint]
Tutorial details
Difficulty level Easy
Root privileges No
Requirements Python
Est. reading time 2m
[/donotprint]

Syntax: Python delete file

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

OR

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

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:

#!/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 

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)
shutil.rmtree(path[, ignore_errors[, onerror]])

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

#!/usr/bin/python
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
try:
	shutil.rmtree(mydir)
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.

🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.

🐧 4 comments so far... add one


CategoryList of Unix and Linux commands
Disk space analyzersdf duf ncdu pydf
File Managementcat cp mkdir tree
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Modern utilitiesbat exa
Network UtilitiesNetHogs dig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg glances gtop jobs killall kill pidof pstree pwdx time vtop
Searchingag grep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
4 comments… add one
  • meow Mar 1, 2013 @ 12:36

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

    • meooooow Mar 5, 2013 @ 15:24

      TIMTOWTDIBSCINABTE …

  • meow Mar 1, 2013 @ 12:42

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

  • mate wierdl Sep 7, 2017 @ 21:10

    Thank you! This was useful.

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre> for code samples. Still have questions? Post it on our forum