Introduction
In this lesson, we will explore the critical aspects of handling files and directories using Python's standard library modules: os, shutil, and pathlib. These modules provide robust tools for navigating the filesystem, managing files and directories, and ensuring cross-platform compatibility. You will learn how to navigate directories, manipulate files and folders using these modules, and handle file paths effectively.
Navigating Directories
Python provides several ways to navigate and inspect directories effectively:
Using os Module
The os module offers functions to interact with the operating system, including directory navigation:
import os
# List all files and directories in the current directory
print(os.listdir('.'))
# Change the current working directory
os.chdir('/path/to/directory')
print(os.getcwd())
Using pathlib Module
The pathlib module introduces an object-oriented approach to manage filesystem paths:
from pathlib import Path
# Create a Path object for the current directory
current_dir = Path('.')
# Iterating over all files in the directory
for file in current_dir.iterdir():
print(file)
Managing Files and Directories
Creating, Renaming, Moving, and Deleting
Using os and shutil Modules
Here’s how you can manage files and directories:
import os
import shutil
# Create a new directory
os.makedirs('new_folder')
# Rename a directory
os.rename('new_folder', 'renamed_folder')
# Move a file
shutil.move('source.txt', 'destination_directory/')
# Delete a file
os.remove('destination_directory/source.txt')
# Delete a directory
shutil.rmtree('renamed_folder')
Using pathlib Module
from pathlib import Path
# Create a new directory
new_dir = Path('new_directory')
new_dir.mkdir(exist_ok=True)
# Delete a directory
if new_dir.exists():
new_dir.rmdir()
Path Handling with pathlib
Absolute and Relative Paths
pathlib provides a clear API to work with absolute and relative paths:
from pathlib import Path
# Define a relative path
rel_path = Path('some_file.txt')
# Convert to absolute path
abs_path = rel_path.resolve()
print(abs_path)
High-Level Operations with shutil
Copying, Archiving, and Extracting
shutil provides high-level file operations, such as copying and archiving:
import shutil
# Copy a file
shutil.copy('file.txt', 'copy_file.txt')
# Create a ZIP archive
shutil.make_archive('archive_name', 'zip', 'directory_to_archive')
# Extracting from a ZIP archive
shutil.unpack_archive('archive_name.zip', 'extracted_directory')
Error Handling in File I/O
When dealing with files, handling potential errors is crucial for robust applications:
import os
try:
with open('non_existent_file.txt', 'r') as file:
content = file.read()
except FileNotFoundError:
print("File not found, please check the file path.")
except IOError:
print("An error occurred while reading the file.")
Summary / Key Takeaways
In this lesson on Handling files and directories, you have learned:
- Directory Navigation: Use
osandpathlibfor listing and navigating directories. - File and Directory Management: Efficiently create, move, rename, and delete using
osandshutil. - Path Handling: Utilize
pathlibfor object-oriented path operations, handling both absolute and relative. - High-Level Operations with
shutil: Copy, archive, and extract directories easily with provided functions. - Error Handling: Implement robust file I/O operations with proper error handling to ensure cross-platform compatibility.
