📂 os Module

Last Updated: 25th August 2025


The os module provides a way to interact with the operating system. It allows you to create, remove, and modify files, directories, and processes. Use module with try and except block for handling errors if there is required.


List of OS Functions:

  • os.getcwd(): Returns the current working directory.
import os
# Get the current working directory
current_dir = os.getcwd()
print("Current working directory:", current_dir)
  • os.chdir(path): Changes the current working directory to the specified path.
import os

# Change to a specific directory
try:
    os.chdir("/tmp")
    print("Changed to directory:", os.getcwd())
except FileNotFoundError:
    print("Directory does not exist!")
except PermissionError:
    print("Permission denied!")
  • os.listdir(path): Returns a list of the names of the files and directories in the specified path.
import os
# List contents of the current directory
contents = os.listdir(".")
print("Directory contents:", contents)
  • os.mkdir(path): Creates a new directory at the specified path.
import os

# Create a new directory
new_dir = "my_folder"
try:
    os.mkdir(new_dir)
    print(f"Created directory: {new_dir}")
except FileExistsError:
    print(f"Directory {new_dir} already exists!")
  • os.makedirs(path): Creates a directory and any necessary parent directories.Useful for nested directory creation.
import os

# Create nested directories
new_path = "parent/child/grandchild"
try:
    os.makedirs(new_path, exist_ok=True)  # exist_ok prevents error if directory exists
    print(f"Created directories: {new_path}")
except OSError as e:
    print(f"Error: {e}")
  • os.rmdir(path): Removes the specified empty directory. Raises an error if the directory is not empty or doesn’t exist.
import os

# Create and remove an empty directory
dir_path = "empty_folder"
os.mkdir(dir_path)
try:
    os.rmdir(dir_path)
    print(f"Removed directory: {dir_path}")
except OSError as e:
    print(f"Error: {e}")
  • os.removedirs(path):Removes a directory and its empty parent directories recursively until a non-empty directory is encountered.
import os

# Create nested directories and remove them
nested_path = "parent/child/grandchild"
os.makedirs(nested_path)
try:
    os.removedirs(nested_path)
    print(f"Removed directories: {nested_path}")
except OSError as e:
    print(f"Error: {e}")
  • os.remove(path): Removes the specified file. Raises an error if the file does not exist.
import os

# Create a file and then remove it
file_path = "temp.txt"
try:
    os.remove(file_path)
    print(f"Removed file: {file_path}")
except FileNotFoundError:
    print(f"File {file_path} does not exist!")
  • os.rename(old_path, new_path): Renames a file or directory. Raises an error if the old path does not exist.
import os
old_name = "old.txt"
new_name = "new.txt"
try:
    os.rename(old_name, new_name)
    print(f"Renamed {old_name} to {new_name}")
except FileNotFoundError:
    print(f"File {old_name} not found!")
  • os.path.exists(path): Checks if the specified path exists.
import os

# Check if a file exists
file_path = "existing_file.txt"
if os.path.exists(file_path):
    print(f"File {file_path} exists!")
else:
    print(f"File {file_path} does not exist!")
  • os.path.isfile(path): Checks if the specified path is a file.
import os

# Check if a file exists
file_path = "existing_file.txt"
if os.path.isfile(file_path):
    print(f"File {file_path} exists!")
else:
    print(f"File {file_path} does not exist!")
  • os.path.isdir(path): Checks if the specified path is a directory.
import os

# Check if a directory exists
dir_path = "existing_directory"
if os.path.isdir(dir_path):  # Check if the path is a directory
    print(f"Directory {dir_path} exists!")
else:
    print(f"Directory {dir_path} does not exist!")
  • os.path.getsize(path): Returns the size of the file in bytes.
import os

# Get the size of a file
file_path = "existing_file.txt"
file_size = os.path.getsize(file_path)
print(f"File size: {file_size} bytes")
  • os.path.join(path1, path2, ...): Joins multiple path components into a single path.
import os

# Join paths
path1 = "parent"
path2 = "child"
joined_path = os.path.join(path1, path2)
print(f"Joined path: {joined_path}")

# Join paths with multiple components
folder = "my_folder"
file = "data.txt"
full_path = os.path.join(folder, file)
print("Joined path:", full_path)
  • os.path.abspath(path): Returns the absolute path of the specified path, resolving any relative paths.
import os

# Get absolute path
relative_path = "example.txt"
absolute_path = os.path.abspath(relative_path)
print("Absolute path:", absolute_path)
  • os.path.split(path): Splits a path into a tuple of (head, tail), where head is the directory path and tail is the last component (file or directory name).
import os

# Split a path
path = "/home/user/documents/file.txt"
head, tail = os.path.split(path)
print(f"Head: {head}, Tail: {tail}")
  • os.path.splitext(path): Splits a path into a tuple of (root, ext), where root is the path without the extension and ext is the file extension.
import os

# Split a path into root and extension
path = "/home/user/documents/file.txt"
root, ext = os.path.splitext(path)
print(f"Root: {root}, Extension: {ext}")
  • os.path.basename(path): Returns the last component of a path.
import os

# Get the last component of a path
path = "/home/user/documents/file.txt"
basename = os.path.basename(path)
print(f"Last component: {basename}") # file.txt