Delete a File and Directory in Python

  1. Delete a File in Python
  2. Delete a Directory in Python

This tutorial introduces how to delete a file or directory in Python 2.7 and Python 3.

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 the 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")
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Python File

  • Delete Files and Directories Using Python
  • Read Specific Lines From a File in Python
  • Related Article - Python Dictionary

  • Get All the Files of a Directory
  • Write String to a File in Python