2 min read

Python OS Module

The os module provides a portable way of using operating system dependent functionality. It allows you to interact with the underlying operating system, including file system operations, environment variables, and process management.

Importing the Module

import os

File and Directory Operations

Getting Current Working Directory

cwd = os.getcwd()
print(cwd)

Changing Directory

os.chdir('/path/to/directory')

Listing Files

files = os.listdir('.')
print(files)

Creating Directories

# Create a single directory
os.mkdir('new_folder')

# Create directory tree (nested directories)
os.makedirs('parent/child/grandchild')

Removing Files and Directories

# Remove a file
os.remove('file.txt')

# Remove an empty directory
os.rmdir('empty_folder')

Path Manipulation (os.path)

The os.path submodule provides useful functions on pathnames.

path = '/home/user/docs/file.txt'

# Get the directory name
print(os.path.dirname(path)) # /home/user/docs

# Get the base name (filename)
print(os.path.basename(path)) # file.txt

# Check if path exists
print(os.path.exists(path))

# Join paths intelligently
new_path = os.path.join('/home/user', 'downloads', 'image.png')

Environment Variables

You can access environment variables using os.environ.

# Get an environment variable
user = os.environ.get('USER')

# Set an environment variable (for the current process)
os.environ['MY_VAR'] = 'some_value'

Running System Commands

While subprocess is generally preferred, os.system() is a simple way to run a command.

os.system('echo "Hello World"')

programming/python/python