The os module

The os module provides a way to interact with the operating system. It allows us to perform various operations related to file and directory management, process management, environment variables, and more.

Here are a few practical examples of how you can use the os module:

1. Working with Files and Directories:

The os module provides functions to work with files and directories, such as creating, renaming, deleting, and navigating through them.

import os

# Get the current working directory
current_dir = os.getcwd()
print(current_dir)

# Create a new directory
os.mkdir("new_directory")

# Rename a file or directory
os.rename("old_name.txt", "new_name.txt")

# Delete a file or directory
os.remove("file_to_delete.txt")
os.rmdir("directory_to_delete")

In this code, we import the os module and use its functions to perform various file and directory operations. We get the current working directory using os.getcwd(), create a new directory using os.mkdir(), rename a file or directory using os.rename(), and delete a file or directory using os.remove() and os.rmdir().

2. Running System Commands:

The os module allows us to run system commands using the os.system() function.

import os

# Run a system command
os.system("ls -l")

In this code, we use the os.system() function to run the system command ls -l, which lists the files and directories in the current directory.

3. Environment Variables:

The os module provides functions to access and modify environment variables.

import os

# Get the value of an environment variable
home_dir = os.getenv("HOME")
print(home_dir)

# Set the value of an environment variable
os.environ["MY_VARIABLE"] = "my_value"

In this code, we use os.getenv() to get the value of the HOME environment variable, which stores the path to the user's home directory. We also use os.environ to set the value of a custom environment variable called MY_VARIABLE.

The os module offers many more functions and capabilities for interacting with the operating system. It provides a powerful set of tools to work with files, directories, processes, and environment variables.