How To Delete and Remove File and Directory with Python? – POFTUT

How To Delete and Remove File and Directory with Python?


Python provides different methods and functions in order to remove files and directories. As python provides a  lot of functionalities we can remove files and directories according to our needs. For example, we can remove files those sizes are bigger than 1 MB.

Check If File or Directory Exist

Before removing a file or directory checking if it exist is very convenient way. We can check a file is exist with the exists() function of the os.path module. In the following example we will check different files for their existence.

import os

if os.path.exists("test.txt"):
print("test.txt exist")
else:
print("test.txt do NOT exist")

test.txt exist


status = os.path.exists("test.txt")
#status will be True

status = os.path.exists("text.txt")
#status will be False

status = os.path.exists("/")
#status will be True

status = os.path.exists("/home/ismail")
#status will be True
Check If File or Directory Exist

Remove File with remove() Method

We can use os.remove() function in order to remove a file. We should import the os module in order to use remove function. In this example, we will remove the file named trash.

import os

os.remove("/home/ismail/readme.txt")

os.remove("/home/ismail/test.txt")

os.remove("/home/ismail/Pictures")

#Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
#IsADirectoryError: [Errno 21] Is a directory: '/home/ismail/Pictures'
Remove File with remove() Method

We can see that when we try to remove a directory or folder named “Pictures” we get an error because the remove() method can not be used for removing or deleting directory or folders.

If the specified file is not exist the FileNotFoundError will be thrown as an exception. Another error or exception is if the current user do not have rights to delete file running remove() function will throw the PermissionError. In order to handle this type of errors and exceptions we should use a try-catch mechamism and handle them properly.

LEARN MORE  What is Python Programming?

Handle Exceptions and Errors For File Delete Operation

We can handle previously defined errors and exceptions with the try-catch block. In this part we will hand different exceptions and errors related IsADirectory , FileNotFound , PermissionError .

Handle Exceptions and Errors For File Delete Operation

We can in the above that every remote operations created an error or exception. Now we we will handle all these exception properly and print some information about the exceptions.

import os

try:
os.remove("/home/ismail/notexist.txt")
except OSError as err:
print("Exception handled: {0}".format(err))

# Exception handled: [Errno 2] No such file or directory: '/home/ismail/notexist.txt'


try:
os.remove("/etc/shadow")
except OSError as err:
print("Exception handled: {0}".format(err))

#Exception handled: [Errno 13] Permission denied: '/etc/shadow'



try:
os.remove("/home/ismail/Pictures")
except OSError as err:
print("Exception handled: {0}".format(err))

#Exception handled: [Errno 21] Is a directory: '/home/ismail/Pictures'
Handle Exceptions and Errors For File Delete Operation

Remove File with unlink

unlink is used to remove files. unlink implements exact mechanisms of the remove . unlinkis defined because of to implement Unix philosophy. Look remove for more information.

Remove Empty Directory/Folder with rmdir() Mehtod

As we know Linux provides rmdir command which used to remove empty directories. Python provides the same function under os module. We can only delete empty directories with rmdir.

import os

os.rmdir("/home/ismail/data")

Delete Directory and Contents Recursively with rmtree() Method

How can we delete the directory and its contents? We can not use rmdir because the directory is not empty. We can use shutil module rmtree function.

import shutil

shutil.rmtree("/home/ismail/cache")
Delete Directory and Contents Recursively with rmtree
Delete Directory and Contents Recursively with rmtree

Delete Only Specific File Types or Extensions

While deleting files we may require only delete specific file types or extensions. We can use * wildcard in order to specify file extensions. For example, in order to delete text files, we can specify the *.txt extension. We should also use glob module and functions to create a list of files.

LEARN MORE  What Is Socket In Linux?

In this example, we will list all files with extensions .txt by using glob function. We will use the list name filelist for these files. Then loop over the list to remove files with remove() function one by one.

import glob
import os

filelist=glob.glob("/home/ismail/*.txt")
for file in filelist:
  os.remove(file)
Delete Only Specific File Types or Extensions
Delete Only Specific File Types or Extensions

2 thoughts on “How To Delete and Remove File and Directory with Python?”

Leave a Comment