Deleting Directory or Files using Python

OS module provides different methods for removing directories and files in Python. These are – 

  • Using os.remove()
  • Using os.rmdir()

Using os.remove() Method

os.remove() method in Python is used to remove or delete a file path. This method can not remove or delete a directory. If the specified path is a directory then OSError will be raised by the method.

Example: Suppose the file contained in the folder are:
 

This code removes a file named “file1.txt” from the specified location “D:/Pycharm projects/w3wiki/Authors/Nikhil/”. It uses the os.remove function to delete the file at the specified path.

Python
import os 
file = 'file1.txt'
location = "D:/Pycharm projects/w3wiki/Authors/Nikhil/"
path = os.path.join(location, file) 
os.remove(path) 

Output:


Using os.rmdir()

os.rmdir() method in Python is used to remove or delete an empty directory. OSError will be raised if the specified path is not an empty directory.

Example: Suppose the directories are 

This code attempts to remove a directory named “Geeks” located at “D:/Pycharm projects/”.

It uses the os.rmdir function to delete the directory. If the directory is empty, it will be removed. If it contains files or subdirectories, you may encounter an error.

Python
import os 
directory = "Geeks"
parent = "D:/Pycharm projects/"
path = os.path.join(parent, directory) 
os.rmdir(path) 

Output:

OS Module in Python with Examples

The OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system-dependent functionality.

The *os* and *os.path* modules include many functions to interact with the file system.

Similar Reads

Python-OS-Module Functions

Here we will discuss some important functions of the Python os module :...

Handling the Current Working Directory

Consider Current Working Directory(CWD) as a folder, where Python is operating. Whenever the files are called only by their name, Python assumes that it starts in the CWD which means that name-only reference will be successful only if the file is in the Python’s CWD....

Creating a Directory

There are different methods available in the OS module for creating a directory. These are –...

Listing out Files and Directories with Python

There is os.listdir() method in Python is used to get the list of all files and directories in the specified directory. If we don’t specify any directory, then the list of files and directories in the current working directory will be returned....

Deleting Directory or Files using Python

OS module provides different methods for removing directories and files in Python. These are –...

Commonly Used Functions

Using os.name function...