The pathlib Module
Python’s pathlib module offers a modern, object-oriented approach to handling filesystem paths.
Rather than dealing with raw strings and os.path functions, pathlib allows you to work with Path objects that have methods and operators for common tasks.
This often makes code more readable and less error-prone.
Creating Path Objects
To use pathlib, first import the Path class:
from pathlib import Path
You can create a Path object by passing a string to Path():
data_dir = Path("data/files")
-
This doesn’t create a folder on disk — it’s just a path representation.
-
Printing
data_dirwill show a normalized path (e.g.,data/files). -
Path objects can represent files or directories.
Navigating and Combining Paths
Path objects override the / operator to join paths easily.
Instead of os.path.join, you can write:
base = Path("/home/user")
subdir = base / "documents" / "images"
print(subdir) # Outputs "/home/user/documents/images"
-
This method is intuitive and reduces mistakes with separators.
-
Path.cwd()→ current working directory. -
Path.home()→ user’s home directory.
Checking and Creating Paths
pathlib provides methods to interact with the filesystem:
-
path.exists()→ returnsTrueif the path exists. -
path.is_file()→ checks if it’s a file. -
path.is_dir()→ checks if it’s a directory. -
path.mkdir(parents=True, exist_ok=True)→ creates a directory.
Example:
reports_dir = Path("reports")
if not reports_dir.exists():
reports_dir.mkdir()
This checks if the “reports” folder exists and creates it if not.
Listing Directory Contents
Use .iterdir() to iterate through items in a directory:
for item in reports_dir.iterdir():
print(item.name)
-
Prints the names of files/subfolders.
-
Each item is a Path object and supports methods like
.is_file().
Opening, Reading, Writing
You can open files via pathlib:
-
path_obj.open('r')→ file handle. -
path_obj.read_text()→ read text directly. -
path_obj.write_text()→ write text directly.
(File reading/writing will be covered later in detail.)
Why pathlib?
-
Portable: Automatically uses correct path separators.
-
Readable: Cleaner syntax for working with paths.
-
Powerful: Methods like
.glob('*.png')make file searching easier.
