October 13, 2024

Python OS Module

The os module in Python provides a way of using operating system-dependent functionality like reading or writing to the file system, managing directories, and interacting with the operating system. This module is part of the Python standard library, so it is available in every Python installation.

1. Importing the os Module

To use the functions provided by the os module, you need to import it first:

import os

2. Working with Directories

The os module provides several functions to create, remove, and navigate directories.

2.1. Get the Current Working Directory

os.getcwd() returns the current working directory as a string.

import os

cwd = os.getcwd()
print("Current Working Directory:", cwd)

2.2. Change the Current Working Directory

os.chdir(path) changes the current working directory to the specified path.

import os

os.chdir('/path/to/directory')
print("Changed Working Directory:", os.getcwd())

2.3. List Files and Directories

os.listdir(path) returns a list of all files and directories in the specified path. If no path is specified, it lists the contents of the current directory.

import os

contents = os.listdir('.')
print("Directory Contents:", contents)

2.4. Create a Directory

os.mkdir(path) creates a new directory at the specified path.

import os

os.mkdir('new_directory')
print("Directory 'new_directory' created")

2.5. Remove a Directory

os.rmdir(path) removes the directory at the specified path. The directory must be empty.

import os

os.rmdir('new_directory')
print("Directory 'new_directory' removed")

2.6. Create Intermediate Directories

os.makedirs(path) creates intermediate directories if they do not exist. It is useful when you need to create multiple levels of directories at once.

import os

os.makedirs('parent_dir/child_dir')
print("Directories 'parent_dir/child_dir' created")

2.7. Remove Directories Recursively

os.removedirs(path) removes directories recursively, starting from the leaf directory back to the root, as long as they are empty.

import os

os.removedirs('parent_dir/child_dir')
print("Directories 'parent_dir/child_dir' removed")

3. Working with Files

The os module provides functions for interacting with the file system, including checking, renaming, and deleting files.

3.1. Check if a Path Exists

os.path.exists(path) returns True if the specified path exists, otherwise False.

import os

file_exists = os.path.exists('example.txt')
print("Does 'example.txt' exist?", file_exists)

3.2. Check if a Path is a File or Directory

  • os.path.isfile(path): Returns True if the specified path is a file.
  • os.path.isdir(path): Returns True if the specified path is a directory.
import os

is_file = os.path.isfile('example.txt')
is_dir = os.path.isdir('example_directory')

print("'example.txt' is a file:", is_file)
print("'example_directory' is a directory:", is_dir)

3.3. Rename a File or Directory

os.rename(src, dst) renames a file or directory from src to dst.

import os

os.rename('old_name.txt', 'new_name.txt')
print("'old_name.txt' renamed to 'new_name.txt'")

3.4. Delete a File

os.remove(path) deletes the file at the specified path.

import os

os.remove('example.txt')
print("'example.txt' deleted")

4. Environment Variables

The os module allows you to interact with the environment variables of the operating system.

4.1. Get an Environment Variable

os.getenv(key, default=None) returns the value of the environment variable key. If the variable does not exist, it returns default.

import os

home_dir = os.getenv('HOME', 'Not Set')
print("Home Directory:", home_dir)

4.2. Set an Environment Variable

os.putenv(key, value) sets the environment variable key to value. Note that os.putenv() does not update the os.environ dictionary; changes are not reflected in the environment of the Python process itself.

import os

os.putenv('MY_ENV_VAR', 'some_value')
print("Environment variable 'MY_ENV_VAR' set to 'some_value'")

4.3. Access All Environment Variables

os.environ returns a dictionary-like object containing all the environment variables.

import os

env_vars = os.environ
print(env_vars)

5. Working with Paths

The os.path submodule provides functions to manipulate file paths in a platform-independent manner.

5.1. Join Paths

os.path.join(path, *paths) joins one or more path components intelligently.

import os

full_path = os.path.join('parent_dir', 'child_dir', 'file.txt')
print("Full Path:", full_path)

5.2. Get the Directory Name

os.path.dirname(path) returns the directory name of the specified path.

import os

directory = os.path.dirname('/path/to/file.txt')
print("Directory Name:", directory)

5.3. Get the Base Name

os.path.basename(path) returns the base name (the last component) of the specified path.

import os

basename = os.path.basename('/path/to/file.txt')
print("Base Name:", basename)

5.4. Split the Path

os.path.split(path) splits the path into a tuple (head, tail), where tail is the last component and head is everything leading up to it.

import os

head, tail = os.path.split('/path/to/file.txt')
print("Head:", head)
print("Tail:", tail)

6. Running External Commands

The os module allows you to run external commands directly from your Python script.

6.1. Execute a Command

os.system(command) runs the specified command in the system shell.

import os

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