How to Delete a File and Directory

Delete a file in Python

os.remove() function deletes the file if this file exists, raises the corresponding exceptions if the file doesn’t exist, or it is not a file, or the user doesn’t have the permission to delete it.

You could first check whether the file exists with os.path.isfile() function or use try...except exception handling to capture the error. We recommend the exception handling as better practice.

import os

fileTest = r"C:\Test\test.txt"

try:
    os.remove(fileTest)
except OSError as e:
    print(e)
else:
    print("File is deleted successfully")

It prints File is deleted successfully if file is deleted, and it prints [WinError 2] The system cannot find the file specified: 'C:\\Test\\test.txt' if the file doesn’t exist. And you will get [WinError 5] Access is denied: 'C:\\Test\\test.txt' if the user doesn’t have the permission to delete it.

Delete a directory in Python

shutil.rmtree() deletes an entire directory tree, in other words, all the files and sub-directories in it. It raises exceptions if the input argument is not a directory, or it doesn’t exist or the user doesn’t have the permission to delete it.

import shutil

pathTest = r"C:\Test"

try:
    shutil.rmtree(pathTest)
except OSError as e:
    print(e)
else:
    print("The directory is deleted successfully")