Python OS Module: Managing System Operations

Learn how to use Python's OS module to automate operating system tasks such as creating and removing directories, fetching directory contents, and managing the current working directory. Start by importing the module with import os and explore its powerful functions for efficient system management.



Python - OS Module

It is possible to perform various operating system tasks automatically using Python's OS module. This module provides functions for creating and removing directories (folders), fetching directory contents, changing and identifying the current directory, etc.

To start using the OS module, import it using import os before utilizing its functions.

Getting Current Working Directory

The getcwd() function retrieves the current working directory.

Example

import os

print(os.getcwd())  # Output: 'C:\\Python37'
Output

C:\\Python37

Creating a Directory

The mkdir() function creates a new directory.

Example

import os

os.mkdir("C:\\NewPythonProject")

Changing the Current Working Directory

The chdir() function changes the current working directory.

Example

import os

os.chdir("C:\\NewPythonProject")
print(os.getcwd())  # Output: 'C:\\NewPythonProject'

Removing a Directory

The rmdir() function removes a directory.

Example

import os

os.rmdir("C:\\NewPythonProject")

List Files and Sub-directories

The listdir() function lists all files and directories in a specified directory.

Example

import os

print(os.listdir("C:\\Python37"))
Output

['.config', '.dotnet', 'python']

If no directory is specified, it lists files and directories in the current working directory.

Example

import os

print(os.listdir())