You can use either remove("/path/to/file") or unlink("/file/path") to remove (delete) the file path.
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:
- 30 Handy Bash Shell Aliases For Linux / Unix / Mac OS X
- Top 30 Nmap Command Examples For Sys/Network Admins
- 25 PHP Security Best Practices For Sys Admins
- 20 Linux System Monitoring Tools Every SysAdmin Should Know
- 20 Linux Server Hardening Security Tips
- Linux: 20 Iptables Examples For New SysAdmins
- Top 20 OpenSSH Server Best Security Practices
- Top 20 Nginx WebServer Best Security Practices
- 20 Examples: Make Sure Unix / Linux Configuration Files Are Free From Syntax Errors
- 15 Greatest Open Source Terminal Applications Of 2012

- My 10 UNIX Command Line Mistakes
- Top 10 Open Source Web-Based Project Management Software
- Top 5 Email Client For Linux, Mac OS X, and Windows Users
- The Novice Guide To Buying A Linux Laptop












{ 3 comments… read them below or add one }
The best way deleting files within Python is using shutil module, so this article is sorta useless.
TIMTOWTDIBSCINABTE …
and note that you’d better using “tempfile” module to work with temporary files, it is secure and does more stuff automatically for you.