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.
Get the current working directory
import os current_dir = os.getcwd() print(current_dir)
Create a new directory
os.mkdir("new_directory")
Let's also create a file so we can work with it later.
open("new.txt", "w").close()
List all files and directories in the current directory
os.listdir()
Rename a file or directory
os.rename("new_directory", "renamed_directory") os.listdir()
Delete a file or directory
os.remove("new.txt") os.rmdir("renamed_directory") os.listdir()
2. Environment Variables:
The os
module provides functions to access and modify environment variables.
Get the value of an environment variable
import os home_dir = os.getenv("HOME") print(home_dir)
Set the value of an environment variable
import os os.environ["MY_VARIABLE"] = "my_value" print(os.environ["MY_VARIABLE"])
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
.
3. Running System Commands:
The os
module allows us to run system commands using the os.system()
function.
import os # Run a system command to list all files and directories 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.
We learned how to list and manipulate files or directories with the os
module. For advanced use cases such as searching for files based on a pattern, read about the glob module.