Delete a file or folder in python

file_system_delete_file

Skill - Delete a file or folder in python

Table of Contents

Skills Required

Please make sure to have all the skills mentioned above to understand and execute the code mentioned below. Go through the above skills if necessary for reference or revision


In this post, we will learn to delete a file or folder in python using remove and rmdir functions

Delete a file using ‘remove’ function

# import the os module
import os

# specify the file we desire to delete
fPath = r'C:\Users\Nagasudhir\Documents\test.txt'

# check if the file exists first
fileExists = os.path.exists(fPath)

if fileExists:
    # use remove function to delete the file if it exists
    os.remove(fPath)  
else:  
    print("File does not exist")

We checked if the file exists at first because, remove function will raise an OSError if the desired file does not exist.

Delete a folder along with sub-folders and files using ‘shutil.rmtree’ function

# import the os module and shutil module
import shutil
import os

# specify the folder we desire to delete
fPath = r'C:\Users\Nagasudhir\UnwantedFolder'

# check if folder is present using isdir function
folderExists = os.path.isdir(fPath)

if folderExists:
    # use remove function to delete the file if it exists
    shutil.rmtree(fPath)  
else:  
    print("Folder does not exist")

Video

The video for this post can be seen here

Online Interpreter

Although we recommend to practice the above examples in Visual Studio Code, you can run these examples online at https://www.tutorialspoint.com/execute_python_online.php

References


Table of Contents

Comments