Working with Directories in Python

The OS module in Python offers a comprehensive array of functions designed to facilitate interaction with the operating system. It encompasses an interface to a multitude of operating system-specific functionalities, encompassing the manipulation of processes, files, file descriptors, directories, and other intricate "low-level" attributes inherent to the operating system's structure.

Current Working Directory

The getcwd() function in Python retrieves the pathway to the present working directory. This directory serves as the reference point for the operating system to convert a relative file name into its absolute counterpart.

example
import os cur_dir = os.getcwd() print(cur_dir)

List Directory Contents

The listdir() function in Python furnishes the content present within a directory, offering a list of items encapsulated within it.

example
import os contents = os.listdir() print(contents)

Create a new Directory/Folder

The mkdir() method in Python facilitates the creation of a novel directory. However, it will trigger an error if the designated parent directory does not exist prior to the operation.

example
import os os.mkdir("Temp")

The above example create a new directory "Temp" in the current path.

Creating Subdirectories

import os os.makedirs("Temp/temp1/temp2/")

Deleting an empty Directory/Folder

The rmdir() method in Python is employed to erase an empty directory or folder from the file system.

example
import os os.rmdir("Temp")

Renaming a directory/folder

The os.rename() method in Python facilitates the renaming of a folder, enabling the transition from an old name to a new one within the file system.

example
import os os.rename("Temp","Temp11")

Conclusion

The os module offers a range of functions for interacting with the operating system, particularly regarding directory manipulation. Functions like getcwd() retrieve the current working directory, listdir() provide directory content, mkdir() create new directories, and rmdir() delete empty directories. Additionally, os.rename() is used to rename folders, collectively enabling efficient directory management within Python programs.