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.
exampleList Directory Contents
The listdir() function in Python furnishes the content present within a directory, offering a list of items encapsulated within it.
exampleCreate 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.
exampleThe above example create a new directory "Temp" in the current path.
Creating Subdirectories
Deleting an empty Directory/Folder
The rmdir() method in Python is employed to erase an empty directory or folder from the file system.
exampleRenaming 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.
exampleConclusion
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.