In this lesson, you will learn how to extract vital information about your files, such as their size, existence, and internal properties, using the object-oriented pathlib module.
Moving Beyond Strings
While we’ve previously learned how to construct cross-platform paths safely, a path object is more than just a file location; it is a gateway to the file's metadata. Instead of relying on manual string parsing or legacy modules, we use the Path object to query the operating system directly about the state of a file.
Inspecting Path Properties
Once you have defined a Path object, you can immediately check for existence using the .exists() method, which returns a boolean. This is essential for building robust pipelines that avoid FileNotFoundError.
To inspect a file’s characteristics, we use properties and methods directly on the object. For example, to find the file extension, we don't need to split strings by dots; we simply access the .suffix attribute.
from pathlib import Path
file_path = Path("data_report.csv")
if file_path.exists():
# Retrieve file size in bytes
size = file_path.stat().st_size
# Retrieve the file extension
ext = file_path.suffix
print(f"File '{file_path.name}' is {size} bytes and is a {ext} file.")
else:
print("The file does not exist.")
Accessing Metadata with .stat()
The .stat() method is the workhorse of file inspection. It returns a stat_result object containing system-level details, such as the file's size (st_size), the time of the last modification (st_mtime), and ownership information.
By treating the path as an object, your code remains clean and cross-platform compatible. You aren't just manipulating text; you are querying the filesystem’s own records. This object-oriented approach allows you to seamlessly integrate file checks into your functional pipelines—for instance, filtering a list of file paths by checking if their .suffix is .csv before processing them.
Key Takeaway: Use the pathlib.Path object’s properties like .suffix and methods like .stat() to query file metadata dynamically, keeping your code readable and platform-independent.