Exploring the Python OS Module
The os module in Python provides a way to interact with the operating system. It contains functions for file and directory manipulation, accessing environment variables, executing system commands, and more. In this guide, we will explore how to use the os module for various tasks.
Quick Links
Importing the OS Module
Before using any functions in the os module, you need to import it. The os module is part of Python's standard library, so no external installation is required.
# To import the os module
import os
# Now you can use any function from the os module like os.getcwd(), os.listdir(), os.mkdir(), etc.
# To import the os module
import os
# Now you can use any function from the os module like os.getcwd(), os.listdir(), os.mkdir(), etc.
After importing the os module, you can call its functions with the os. prefix. For example, to get the current working directory, use os.getcwd(), or to list the files in a directory, use os.listdir().
OS Module Functions
The os module contains several functions for interacting with the operating system. Below are some commonly used functions:
Function | Description |
---|---|
getcwd() | Returns the current working directory |
mkdir() | Creates a new directory |
rmdir() | Removes an empty directory |
rename() | Renames a file or directory |
environ | Dictionary-like object representing the user's environment variables |
system() | Executes a system command (like running shell commands) |
os.path | Submodule for pathname manipulations |
chdir() | Changes the current working directory to the specified path |
getpid() | Returns the current process ID |
getppid() | Returns the parent process ID |
getlogin() | Returns the name of the user logged into the terminal |
umask() | Sets or gets the current process’s file mode creation mask |
makedirs() | Creates a directory and all intermediate directories if they do not exist |
remove() | Deletes a file path |
chown() | Changes the owner and group of a file |
getuid() | Returns the current process’s user ID |
getgid() | Returns the current process’s group ID |
putenv() | Sets an environment variable |
getenv() | Gets the value of an environment variable |
listdir() | Lists files and directories in a specified directory |
link() | Creates a hard link to a file |
symlink() | Creates a symbolic link to a file |
readlink() | Returns the path that the symbolic link points to |
walk() | Generates the file names in a directory tree by walking either top-down or bottom-up through the directory tree |
stat() | Returns status information about a specified file |
lstat() | Similar to stat(), but it does not follow symbolic links |
fstat() | Returns status information about an open file descriptor |
getgroups() | Returns a list of group IDs for the current process |
link() | Creates a hard link to a file |
system() | Runs a system command (such as a shell command) |
getcwdb() | Returns the current working directory as a bytes object |
chroot() | Changes the root directory of the current process |
Examples of OS Module Functions
Below are examples demonstrating how to use some of the most commonly used functions from the os module:
import os
# Example 1: getcwd()
# Returns the current working directory
current_directory = os.getcwd()
print("Current Directory:", current_directory)
# Example 2: listdir()
# Returns a list of files and directories in the given directory
files_and_dirs = os.listdir('.')
print("Files and Directories:", files_and_dirs)
# Example 3: mkdir()
# Creates a new directory
os.mkdir('new_directory')
print("New directory created.")
# Example 4: remove()
# Deletes a file
os.remove('file_to_delete.txt')
print("File deleted.")
# Example 5: rmdir()
# Removes an empty directory
os.rmdir('empty_directory')
print("Empty directory removed.")
# Example 6: rename()
# Renames a file or directory
os.rename('old_name.txt', 'new_name.txt')
print("File renamed.")
# Example 7: environ()
# Returns a dictionary representing the user's environment variables
env_variables = os.environ
print("Environment Variables:", env_variables)
# Example 8: system()
# Executes a system command
os.system('echo "Hello, world!"')
print("System command executed.")
# Example 9: chdir()
# Changes the current working directory to the specified path
os.chdir('/path/to/new/directory')
print("Directory changed.")
# Example 10: getpid()
# Returns the current process ID
pid = os.getpid()
print("Process ID:", pid)
# Example 11: getppid()
# Returns the parent process ID
ppid = os.getppid()
print("Parent Process ID:", ppid)
# Example 12: getlogin()
# Returns the name of the user logged into the terminal
login_user = os.getlogin()
print("Logged in User:", login_user)
# Example 13: umask()
# Sets or gets the current process’s file mode creation mask
current_umask = os.umask(0o022)
print("File mode creation mask:", current_umask)
# Example 14: makedirs()
# Creates directories, including intermediate directories if necessary
os.makedirs('new/parent/directory')
print("Intermediate directories created.")
# Example 15: link()
# Creates a hard link to a file
os.link('file.txt', 'hard_link.txt')
print("Hard link created.")
# Example 16: symlink()
# Creates a symbolic link to a file
os.symlink('file.txt', 'symlink.txt')
print("Symbolic link created.")
# Example 17: readlink()
# Returns the path that the symbolic link points to
link_target = os.readlink('symlink.txt')
print("Symbolic link points to:", link_target)
# Example 18: walk()
# Generates file names in a directory tree by walking through it top-down or bottom-up
for dirpath, dirnames, filenames in os.walk('.'):
print(f"Current Path: {dirpath}")
print(f"Directories: {dirnames}")
print(f"Files: {filenames}")
# Example 19: stat()
# Returns status information about a specified file
file_status = os.stat('file.txt')
print("File Status:", file_status)
# Example 20: getuid()
# Returns the current process’s user ID
uid = os.getuid()
print("User ID:", uid)
# Example 21: getgid()
# Returns the current process’s group ID
gid = os.getgid()
print("Group ID:", gid)
# Example 22: putenv()
# Sets an environment variable
os.putenv('MY_VAR', 'value')
print("Environment variable set.")
# Example 23: getenv()
# Gets the value of an environment variable
my_var_value = os.getenv('MY_VAR')
print("Environment variable value:", my_var_value)
# Example 24: getcwdb()
# Returns the current working directory as a bytes object
current_directory_bytes = os.getcwdb()
print("Current Directory (bytes):", current_directory_bytes)
# Example 25: chroot()
# Changes the root directory for the current process
# Note: This function requires superuser privileges and may not work in all environments
# Use this function with caution, especially on shared or production systems.
# os.chroot('/path/to/new/root')
# print("Root directory changed.")
import os
# Example 1: getcwd()
# Returns the current working directory
current_directory = os.getcwd()
print("Current Directory:", current_directory)
# Example 2: listdir()
# Returns a list of files and directories in the given directory
files_and_dirs = os.listdir('.')
print("Files and Directories:", files_and_dirs)
# Example 3: mkdir()
# Creates a new directory
os.mkdir('new_directory')
print("New directory created.")
# Example 4: remove()
# Deletes a file
os.remove('file_to_delete.txt')
print("File deleted.")
# Example 5: rmdir()
# Removes an empty directory
os.rmdir('empty_directory')
print("Empty directory removed.")
# Example 6: rename()
# Renames a file or directory
os.rename('old_name.txt', 'new_name.txt')
print("File renamed.")
# Example 7: environ()
# Returns a dictionary representing the user's environment variables
env_variables = os.environ
print("Environment Variables:", env_variables)
# Example 8: system()
# Executes a system command
os.system('echo "Hello, world!"')
print("System command executed.")
# Example 9: chdir()
# Changes the current working directory to the specified path
os.chdir('/path/to/new/directory')
print("Directory changed.")
# Example 10: getpid()
# Returns the current process ID
pid = os.getpid()
print("Process ID:", pid)
# Example 11: getppid()
# Returns the parent process ID
ppid = os.getppid()
print("Parent Process ID:", ppid)
# Example 12: getlogin()
# Returns the name of the user logged into the terminal
login_user = os.getlogin()
print("Logged in User:", login_user)
# Example 13: umask()
# Sets or gets the current process’s file mode creation mask
current_umask = os.umask(0o022)
print("File mode creation mask:", current_umask)
# Example 14: makedirs()
# Creates directories, including intermediate directories if necessary
os.makedirs('new/parent/directory')
print("Intermediate directories created.")
# Example 15: link()
# Creates a hard link to a file
os.link('file.txt', 'hard_link.txt')
print("Hard link created.")
# Example 16: symlink()
# Creates a symbolic link to a file
os.symlink('file.txt', 'symlink.txt')
print("Symbolic link created.")
# Example 17: readlink()
# Returns the path that the symbolic link points to
link_target = os.readlink('symlink.txt')
print("Symbolic link points to:", link_target)
# Example 18: walk()
# Generates file names in a directory tree by walking through it top-down or bottom-up
for dirpath, dirnames, filenames in os.walk('.'):
print(f"Current Path: {dirpath}")
print(f"Directories: {dirnames}")
print(f"Files: {filenames}")
# Example 19: stat()
# Returns status information about a specified file
file_status = os.stat('file.txt')
print("File Status:", file_status)
# Example 20: getuid()
# Returns the current process’s user ID
uid = os.getuid()
print("User ID:", uid)
# Example 21: getgid()
# Returns the current process’s group ID
gid = os.getgid()
print("Group ID:", gid)
# Example 22: putenv()
# Sets an environment variable
os.putenv('MY_VAR', 'value')
print("Environment variable set.")
# Example 23: getenv()
# Gets the value of an environment variable
my_var_value = os.getenv('MY_VAR')
print("Environment variable value:", my_var_value)
# Example 24: getcwdb()
# Returns the current working directory as a bytes object
current_directory_bytes = os.getcwdb()
print("Current Directory (bytes):", current_directory_bytes)
# Example 25: chroot()
# Changes the root directory for the current process
# Note: This function requires superuser privileges and may not work in all environments
# Use this function with caution, especially on shared or production systems.
# os.chroot('/path/to/new/root')
# print("Root directory changed.")
What's Next?
Continue to the next guide to dive into the sys module and enhance your understanding of Python’s core capabilities.