Python Delete/Remove a File If Exists On Disk

How can I check if a file exists in a directory with Python and then delete/remove it using python program?

[donotprint]
Tutorial details
DifficultyEasy (rss)
Root privilegesNo
RequirementsPython
Time2m
[/donotprint]You can easily check if a file exists, in a current directory using the following python syntax:

ADVERTISEMENTS

os.path.isfile(filename)

Next, you can use the following syntax to delete the file:

os.remove(filename)

Check If a File Exists and Then Delete It in Python

#!/usr/bin/python
import os
 
## get input ##
filename=raw_input("Type file name to remove: ")
 
## delete only if file exists ##
if os.path.exists(filename):
    os.remove(filename)
else:
    print("Sorry, I can not remove %s file." % filename)

Sample outputs:

Fig. 01: remove.py in action

Fig. 01: remove.py in action

A Better Option To Delete A File In Python

The following code gives an error information when it can not delete the given file name:

#!/usr/bin/python
import os
 
## get input ##
filename=raw_input("Type file name to remove: ")
 
## check if a file exists on disk ##
## if exists, delete it else show message on screen ##
if os.path.exists(filename):
	try:
		os.remove(filename)
	except OSError, e:
		print ("Error: %s - %s." % (e.filename,e.strerror))
else:  
	print("Sorry, I can not find %s file." % filename)

Sample outputs:

Fig. 02: Updated remove.py to  to check if a file exists and then delete it

Fig. 02: Updated remove.py to check if a file exists and then delete it

References

See python os docs for more information.

🐧 Get the latest tutorials on SysAdmin, Linux/Unix, Open Source/DevOps topics:
CategoryList of Unix and Linux commands
File Managementcat
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilitiesdig 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 jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNCentOS 8 Debian 10 Firewall Ubuntu 20.04

ADVERTISEMENTS
0 comments… add one

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre>, <code>...</code> and <kbd>...</kbd> for code samples.