Python OS Module
The os
module in Python is a standard library module that allows you to interact with the operating system. It enables you to perform operating system-dependent tasks, such as file and directory manipulation, process management, and accessing environment variables.
1. Accessing the os
Module
To use the os
module, you first need to import it:
import os
2. Key Functionalities of the os
Module
File and Directory Operations
- Working with the Current Working Directory
os.getcwd()
: Returns the current working directory.
cwd = os.getcwd()
print("Current Directory:", cwd)
os.chdir(path)
: Changes the current working directory to the specified path.
os.chdir("/path/to/directory")
2. Creating and Removing Directories
os.mkdir(path)
: Creates a single directory.
os.mkdir("new_folder")
os.makedirs(path)
: Creates directories recursively.
os.makedirs("parent_folder/child_folder")
os.rmdir(path)
: Removes an empty directory.
os.rmdir("new_folder")
os.removedirs(path)
: Removes directories recursively.
os.removedirs("parent_folder/child_folder")
3. Listing Files and Directories
os.listdir(path=".")
: Lists all files and directories in the given path.
items = os.listdir(".")
print(items)
4. Renaming and Deleting Files
os.rename(src, dst)
: Renames a file or directory.
os.rename("old_name.txt", "new_name.txt")
os.remove(path)
: Deletes a file.
os.remove("file.txt")
Environment Variables
- Getting and Setting Environment Variables
os.environ
: A dictionary-like object containing the environment variables.
print(os.environ["PATH"])
os.environ["NEW_VAR"] = "value"
: Sets a new environment variable.
os.environ["MY_VAR"] = "123"
print(os.environ["MY_VAR"])
2. Getting a Specific Environment Variable
os.getenv(key, default=None)
: Gets the value of an environment variable.
home_dir = os.getenv("HOME")
print(home_dir)
Path Manipulations
- Checking Existence and Properties
os.path.exists(path)
: Checks if a path exists.
exists = os.path.exists("file.txt")
print(exists)
os.path.isdir(path)
: Checks if a path is a directory.os.path.isfile(path)
: Checks if a path is a file.
2. Joining and Splitting Paths
os.path.join(path1, path2)
: Joins two or more paths.
full_path = os.path.join("folder", "file.txt")
print(full_path)
os.path.split(path)
: Splits a path into head and tail.
head, tail = os.path.split("/path/to/file.txt")
print("Head:", head)
print("Tail:", tail)
3. Getting File Information
os.path.getsize(path)
: Gets the size of a file in bytes.
size = os.path.getsize("file.txt")
print("File Size:", size, "bytes")
Process Management
- Getting Process Information
os.getpid()
: Gets the current process ID.
print("Process ID:", os.getpid())
os.getppid()
: Gets the parent process ID.
print("Parent Process ID:", os.getppid())
2. Starting New Processes
os.system(command)
: Executes a system command in a subshell.
os.system("ls")
Platform Information
os.name
: Returns the name of the operating system-dependent module imported.
print(os.name) # 'posix' for Unix-like, 'nt' for Windows
os.uname()
: Provides system information (Unix-like systems only).
print(os.uname())
Miscellaneous
- Changing Permissions
os.chmod(path, mode)
: Changes the mode (permissions) of a file or directory.
os.chmod("file.txt", 0o644)
2. Walking a Directory Tree
os.walk(top, topdown=True)
: Generates the file names in a directory tree.
for root, dirs, files in os.walk("."):
print("Root:", root)
print("Directories:", dirs)
print("Files:", files)
Example: Combining Multiple Functions
import os
# Get current working directory
cwd = os.getcwd()
print("Current Directory:", cwd)
# Create a new directory
os.mkdir("test_dir")
# Change to the new directory
os.chdir("test_dir")
print("Changed Directory:", os.getcwd())
# Create a file in the directory
with open("example.txt", "w") as f:
f.write("Hello, world!")
# List contents
print("Directory Contents:", os.listdir("."))
# Clean up
os.remove("example.txt")
os.chdir("..")
os.rmdir("test_dir")
The os
module is a very important tool for tasks that involve interacting with the file system and the operating system.