/    /  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.

 

Example:

Check if file exists, then delete.

 

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

 

Os.rmdir() is used to remove directory.

 

Example:

 

import os
os.rmdir("myfolder")

 

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.