Python os Module

The os module in Python provides a way of using operating system-dependent functionality, such as reading or writing to the file system, handling environment variables, and interacting with the operating system.

Table of Contents

  1. Introduction
  2. Key Functions and Methods
    • os.name
    • os.getcwd
    • os.chdir
    • os.listdir
    • os.mkdir
    • os.makedirs
    • os.remove
    • os.rmdir
    • os.removedirs
    • os.rename
    • os.stat
    • os.system
    • os.environ
    • os.path
  3. Examples
    • Working with Directories
    • Working with Files
    • Interacting with the System
    • Managing Environment Variables
  4. Real-World Use Case
  5. Conclusion
  6. References

Introduction

The os module is a part of the standard library and provides a way to interact with the operating system. It includes functions for file and directory manipulation, process management, and more. This makes it used for performing system-level tasks.

Key Functions and Methods

os.name

Returns the name of the operating system-dependent module imported.

import os
print(os.name)  # 'posix', 'nt', 'os2', 'ce', 'java', 'riscos'

os.getcwd

Returns the current working directory.

import os
print(os.getcwd())

os.chdir

Changes the current working directory.

import os
os.chdir('/path/to/directory')
print(os.getcwd())

os.listdir

Returns a list of the entries in the specified directory.

import os
print(os.listdir('.'))

os.mkdir

Creates a directory.

import os
os.mkdir('new_directory')

os.makedirs

Creates a directory and all intermediate directories.

import os
os.makedirs('new_directory/sub_directory')

os.remove

Removes a file.

import os
os.remove('file.txt')

os.rmdir

Removes a directory.

import os
os.rmdir('directory')

os.removedirs

Removes a directory and all intermediate directories.

import os
os.removedirs('new_directory/sub_directory')

os.rename

Renames a file or directory.

import os
os.rename('old_name.txt', 'new_name.txt')

os.stat

Performs a stat system call on the given path.

import os
print(os.stat('file.txt'))

os.system

Executes a command in the system shell.

import os
os.system('ls -l')

os.environ

A dictionary representing the string environment.

import os
print(os.environ)
print(os.environ['HOME'])

os.path

The os.path module provides a way to perform operations on pathnames.

import os
print(os.path.join('dir', 'file.txt'))
print(os.path.exists('file.txt'))
print(os.path.isdir('dir'))
print(os.path.isfile('file.txt'))

Examples

Working with Directories

import os

# Get current working directory
cwd = os.getcwd()
print(f'Current working directory: {cwd}')

# Change directory
os.chdir('/path/to/directory')
print(f'Changed working directory to: {os.getcwd()}')

# List directory contents
contents = os.listdir('.')
print(f'Directory contents: {contents}')

# Create a new directory
os.mkdir('new_dir')
print('Created directory: new_dir')

# Remove a directory
os.rmdir('new_dir')
print('Removed directory: new_dir')

Working with Files

import os

# Create a new file
with open('test_file.txt', 'w') as f:
    f.write('Hello, World!')

# Rename the file
os.rename('test_file.txt', 'renamed_file.txt')
print('File renamed to: renamed_file.txt')

# Remove the file
os.remove('renamed_file.txt')
print('Removed file: renamed_file.txt')

Interacting with the System

import os

# Execute a system command
os.system('echo Hello, World!')

Managing Environment Variables

import os

# Get an environment variable
home_dir = os.environ.get('HOME')
print(f'Home directory: {home_dir}')

# Set an environment variable
os.environ['MY_VARIABLE'] = 'value'
print(f'MY_VARIABLE: {os.environ["MY_VARIABLE"]}')

Real-World Use Case

Creating a Project Directory Structure

import os

def create_project_structure(base_path, project_name):
    os.makedirs(os.path.join(base_path, project_name, 'src'))
    os.makedirs(os.path.join(base_path, project_name, 'tests'))
    os.makedirs(os.path.join(base_path, project_name, 'docs'))
    print(f'Created project structure for {project_name}')

# Example usage
create_project_structure('/path/to/projects', 'my_project')

Conclusion

The os module in Python is used for interacting with the operating system. It provides a wide range of functionalities for file and directory manipulation, process management, and environment variable handling, making it essential for many system-level programming tasks.

References

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top