/    /  Python – Deleting file

Python – Deleting file

In this tutorial, we will learn python in detail.


In python OS module helps for interacting with operating system. This module comes under python’s standard utility modules.


Os.remove() module removes or deletes a file path. Here the directory should be empty, else python will display an exception message.



Check if file exists, then delete.


import os
if os.path.exists("file1.txt"):
  print("The file does not exist")


Os.rmdir() is used to remove directory.




import os


shutil.rmtree() function helps to remove the specified directory, removes all subdirectories and all files. Make sure before using this function because python removes everything without checking. For this you need to import shutil.