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