Python os Module – Complete Guide with Examples

Introduction

Python provides a built-in module called the OS Module that allows developers to interact with the operating system directly. The OS Module offers a portable way of using operating system-dependent functionality and helps automate many system-level tasks.

Whether you’re building automation scripts, file management tools, deployment systems, or data processing applications, the OS Module is an essential part of Python programming.

Some common uses of the OS Module include:

  • Working with files and directories
  • Creating and removing folders
  • Renaming files
  • Accessing environment variables
  • Getting system information
  • Running operating system commands
  • Managing file paths

What is the Python OS Module?

The OS Module is a built-in Python module that provides functions for interacting with the operating system.

Note: It acts as a bridge between Python programs and the underlying operating system.

Using the OS Module, developers can:

  • Access file systems
  • Create directories
  • Delete files
  • Retrieve system information
  • Execute shell commands
  • Work with environment variables

The module works across different operating systems such as:

  • Windows
  • Linux
  • macOS

Importing the OS Module

Before using the OS Module, import it:


import os

Example:


import os
print(os.name)

Output (Windows):


nt

Output (Linux/macOS):


posix

Why Use the OS Module?

The OS Module provides several advantages:

1. Automation: Automates repetitive operating system tasks.

2. Cross-Platform Support: Works on multiple operating systems.

3. File Management: Simplifies file and directory operations.

4. System Information: Provides access to system details.

5. Environment Access: Allows interaction with environment variables.

Getting Operating System Name

The os.name attribute returns the operating system type.

Example:


import os
print(os.name)

Possible outputs:

nt
or
posix

Getting Current Working Directory

The getcwd() function returns the current working directory.

Syntax:


os.getcwd()

Example:


import os
print(os.getcwd())

Output:

C:\Projects\Python

(Output varies depending on your system.)

Changing Current Directory

The chdir() function changes the current directory.

Syntax:


os.chdir(path)

Example:


import os
os.chdir("Documents")
print(os.getcwd())

Output:

C:\Users\User\Documents

Listing Files and Directories

The listdir() function displays all files and folders in a directory.

Syntax:


os.listdir(path)

Example:


import os
print(os.listdir())

Output:

[
‘file1.txt’,
‘file2.txt’,
‘images’
]

Creating a Directory

The mkdir() function creates a new directory.

Syntax:


os.mkdir(directory_name)

Example:


import os
os.mkdir("Projects")

Output:

Directory created successfully

Creating Multiple Directories

The makedirs() function creates nested directories.

Example:


import os
os.makedirs(
    "Python/Files/Test"
)

This creates:


Python
 └── Files
      └── Test

Removing a Directory

The rmdir() function removes an empty directory.

Syntax:


os.rmdir(directory_name)

Example:


import os
os.rmdir("Projects")

Removing Nested Directories

The removedirs() function removes nested empty directories.

Example:


import os
os.removedirs(
    "Python/Files/Test"
)

Renaming Files and Directories

The rename() function changes the name of a file or folder.

Syntax:


os.rename(
    old_name,
    new_name
)

Example:


import os
os.rename(
    "old.txt",
    "new.txt"
)

Deleting a File

The remove() function deletes a file.

Syntax:


os.remove(filename)

Example:


import os
os.remove("data.txt")

Checking Whether a File Exists

Example:


import os
print(
    os.path.exists(
        "data.txt"
    )
)

Output:

True
or
False

Working with File Paths

The os.path module provides path-related functions.

Example:


import os
path = os.path.join(
    "folder",
    "file.txt"
)
print(path)

Output:

Windows:

folder\file.txt

Linux/macOS:

folder/file.txt

Getting Absolute Path

Example:


import os
print(
    os.path.abspath(
        "file.txt"
    )
)

Output:

C:\Projects\file.txt

Getting File Name

Example:


import os
path = "/home/user/data.txt"
print(
    os.path.basename(path)
)

Output:

data.txt

Getting Directory Name

Example:


import os
path = "/home/user/data.txt"
print(
    os.path.dirname(path)
)

Output:

/home/user

Environment Variables

Environment variables store configuration settings used by the operating system.

Example:


import os
print(
    os.environ.get(
        "PATH"
    )
)

Output:

System path information

Setting Environment Variables

Example:


import os
os.environ["APP_MODE"] = "Development"
print(
    os.environ["APP_MODE"]
)

Output:

Development

Executing System Commands

The system() function executes operating system commands.

Syntax:


os.system(command)

Example:


import os
os.system("dir")

Windows output:

Directory listing

Linux/macOS:

os.system(“ls”)

Getting Process ID

The getpid() function returns the current process ID.

Example:


import os
print(
    os.getpid()
)

Output:

12345

Walking Through Directories

The walk() function traverses directories recursively.

Example:


import os
for root, dirs, files in os.walk("."):
    print(root)

Output:

Current directory tree

Useful for searching files.

Real-Life Examples:

1. File Organizer


import os
files = os.listdir()
for file in files:
    print(file)

This can be extended to organize files into folders automatically.

2. Backup Folder Creation


import os
if not os.path.exists(
    "Backup"
):
    os.mkdir("Backup")

Creates a backup directory only if it doesn’t already exist.

3. Log File Cleanup


import os
if os.path.exists(
    "log.txt"
):
    os.remove(
        "log.txt"
    )

Used in maintenance scripts.

4. Display Environment Variables


import os
for key, value in os.environ.items():
    print(key, value)

Useful for debugging deployment environments.

Commonly Used OS Module Functions

Function Description
getcwd() Current directory
chdir() Change directory
listdir() List files
mkdir() Create directory
makedirs() Create nested directories
rmdir() Remove directory
rename() Rename file/folder
remove() Delete file
system() Execute command
getpid() Process ID
walk() Traverse directories

Advantages of Python OS Module

Advantage Description
Built-in Module No installation required
Cross-Platform Works on Windows, Linux, and macOS
Automation Support Automates system tasks
Easy File Management Simplifies file operations
Environment Access Reads and modifies environment variables

Common Mistakes

1. Forgetting to Import os

Incorrect:


print(os.getcwd())

Output:

NameError

Correct:


import os

2. Removing Non-Empty Directories

Incorrect:


os.rmdir("Folder")

If the folder contains files:


OSError

3. Hardcoding File Paths

Incorrect:


"C:\\Users\\Admin\\Desktop"

Better:


os.path.join()

4. Deleting Files Without Checking Existence

Incorrect:


os.remove("data.txt")

May raise:

FileNotFoundError

Better:


if os.path.exists("data.txt"):
    os.remove("data.txt")

5. Using system() Without Validation

Executing user-provided commands may create security risks.

Always validate input.

Conclusion

The Python OS Module is one of the most powerful built-in modules for interacting with the operating system. It provides a wide range of functions for managing files, directories, environment variables, system commands, and processes.

Related Python Tutorials