Python OS Module

Introduction

The os module in Python provides functions to interact with the operating system. It allows you to work with files, folders, system paths, and environment variables and execute system commands.


Task you want to doos Module Feature
Get current directoryos.getcwd()
Change directoryos.chdir()
Create/Remove foldersos.mkdir() / os.rmdir()
List files and foldersos.listdir()
Work with environment variablesos.environ
Join file paths safelyos.path.join()
Delete a fileos.remove()
Run system commandsos.system()

Importing OS Module


Directory Operations

Get the current working directory


Create and Delete Directories

Create a new folder

Remove a folder (only if empty)

Create multiple nested directories

Remove nested directories


File Handling

Delete a file

Rename a file


Path Operations (os.path)

FunctionDescription
os.path.join()Safely join folder and file names
os.path.exists()Check if path/file exists
os.path.isdir()Check if the path is file
os.path.isfile()Check if the path is a file
os.path.getsize()Get file size in bytes

Example


Environment Variables

View environment variables

Fetch a specific variable


Run System Commands

Open Command Prompt / Terminal command


Examples of Python OS Module






os doesn’t have copy directly, so use system command



Check File Permissions




Leave a Comment