The os
module in Python provides a way to interact with the operating system, allowing you to perform various tasks such as file operations, directory manipulations, and more. It serves as a bridge between your Python code and the underlying operating system, enabling you to access system-related functionality in a platform-independent manner.
Simple Use Case:
Let’s start with a simple use case: checking the current working directory and creating a new directory if it doesn’t exist.
import os
# Get the current working directory
current_dir = os.getcwd()
print("Current directory:", current_dir)
# Create a new directory
new_dir = "new_directory"
if not os.path.exists(new_dir):
os.mkdir(new_dir)
print("Directory created:", new_dir)
else:
print("Directory already exists:", new_dir)
Listing Files and Folders:
Next, let’s look at how to use the os
module to list all the files and folders in a given directory.
import os
# Define the directory path
directory = "/path/to/directory"
# List all files and folders in the directory
contents = os.listdir(directory)
for item in contents:
print(item)
Walking the Folder Tree:
Finally, let’s explore how to recursively traverse a folder tree and perform operations on each file and directory.
import os
# Define the root directory
root_dir = "/path/to/root/directory"
# Walk the folder tree
for root, dirs, files in os.walk(root_dir):
print("Current directory:", root)
print("Subdirectories:", dirs)
print("Files:", files)
print()
With the os
module in Python, you have the power to interact with the operating system in a flexible and efficient manner. Whether you’re managing files, navigating directories, or executing system commands, the os
module provides the tools you need to get the job done. So go ahead, explore the possibilities, and unlock the full potential of Python’s os
module!