Honestly. Best tutorial learning os Module from Corey Schafer himself from the video https://www.youtube.com/watch?v=tJxcKyFMTGo The Python os
module is a powerful tool for interacting with the operating system. It provides functions to navigate directories, manipulate files, and access environment variables. Make 2 programs to practice in preperation to learn AWS-CLI and boto3.
Program 1: Navigating Directories and Manipulating Files
The first program was an exploration of basic operations within the os
module. It included tasks like navigating directories, listing files, creating and deleting folders, and retrieving file statistics.
Key Concepts and Methods
Navigating Directories
os.getcwd()
: Retrieves the current working directory.os.chdir()
: Changes the current working directory.
home_dir = os.path.expanduser("~")
print(f"Home directory is: {home_dir}")
os.chdir(home_dir + "/Fred/learntocloud/LTC_Phase_2/python_basics/OS_Module")
print(f"New directory is: {os.getcwd()}")
Listing Files
os.listdir()
: Lists all files and folders in the current directory.
list_of_current_dir = os.listdir()
print(f"Print out current directory in list form: \n{list_of_current_dir}")
Creating and Deleting Folders
os.mkdir()
: Creates a single directory.os.rmdir()
: Removes a single directory.- Error Handling: Implemented with try-except blocks to handle potential issues like attempting to create a directory that already exists.
file_to_folder = "Kratos_folder"
try:
os.mkdir(file_to_folder)
print(f"Directory {file_to_folder} created successfully.")
except FileExistsError:
print(f"{file_to_folder} already exists, skipping creation.")
# Deleting the directory
try:
os.rmdir(file_to_folder)
print(f"{file_to_folder} removed successfully.")
except Exception as e:
print(f"File was not removed, error: {e}")
Retrieving File Statistics
os.stat(<file>)
: Retrieves stats for a specified file, such as size and modification time.
stats_file = "mimir.json"
print(f"Checking stats for {stats_file}")
print(os.stat(stats_file))
# Convert stat time format to human-readable format
mod_time = os.stat(stats_file).st_mtime
print(f"{stats_file} creation time is {datetime.fromtimestamp(mod_time)}")
Program 2: Manipulating File Paths and Exploring Directory Trees
The second program focused on manipulating file paths and exploring directories. It included joining paths, splitting paths, and using the os.walk()
method to traverse directories.
Key Concepts and Methods
- Manipulating File Paths
os.path.join()
: Joins two paths intelligently.os.path.split()
: Splits a path into a tuple(head, tail)
.os.path.splitext()
: Splits the file name and extension.os.path.basename()
: Returns the final component of a pathname.os.path.dirname()
: Returns the directory name from a path.
home_user = os.path.expanduser("~")
working_dir = os.path.join(home_user, "Fred/learntocloud/LTC_Phase_2/python_basics")
real_file2 = os.path.join(working_dir + "/OS_Module/atreus.txt")
print(f"-BASENAME of path is: \n{os.path.basename(working_dir)}")
print(f"-DIRECTORY name of path is: \n{os.path.dirname(working_dir)}")
print(f"-SPLIT path: \n{os.path.split(working_dir)}")
print(f"-SPLIT path from extension: \n{os.path.splitext(real_file2)}")
Checking Path Existence
os.path.exists()
: Checks if a file or directory exists.os.path.isdir()
: Checks if a path is a directory.os.path.isfile()
: Checks if a path is a file.
fake_file = "/loki.txt"
real_file = "/OS_Module"
print(f"Checking if {fake_file} exists: {os.path.exists(os.path.join(working_dir + fake_file))}")
print(f"Checking if {real_file} exists: {os.path.exists(os.path.join(working_dir + real_file))}")
print(f"Checking if {real_file} is a folder: {os.path.isdir(os.path.join(working_dir + real_file))}")
print(f"Checking if {real_file2} is a file: {os.path.isfile(os.path.join(real_file2))}")
Walking Through Directories
os.walk()
: Generates the file names in a directory tree, walking either top-down or bottom-up.
for dirpath, dirnames, filesnames in os.walk(os.path.dirname(real_file2)):
print("Current Path:", dirpath)
print("Directories:", dirnames)
print("Files:", filesnames)
print("---------")
Conclusion
Through these two programs, I explored key functionalities of the Python os
module. From basic directory navigation to complex file path manipulations, these exercises provided a solid understanding of how to interact with the file system programmatically. Whether creating and deleting directories, checking file existence, or navigating directory trees, the os
module is an essential tool for Python developers working with the operating system.
Highlighted os
Module Methods
os.getcwd()
: Retrieve the current directory.os.chdir()
: Change the current directory.os.listdir()
: List folders and files.os.stat()
: Get file statistics.os.path.exists()
,os.path.isdir()
,os.path.isfile()
: Check if a file or directory exists, or if a path is a directory or file.os.mkdir()
,os.rmdir()
: Create or remove directories.os.path.expanduser()
: Expand~
to the home directory.os.path.join()
,os.path.split()
,os.path.splitext()
: Manipulate file paths.os.path.basename()
,os.path.dirname()
: Extract components from a path.
I wanted to learn to effectively navigate and manipulate the file system in Python, making my future scripts more powerful and versatile when working with AWS CLI and boto3.