Course contentsShow
← Python
Lesson 361 of 1,0606. Error Handling and File I/OFree lesson

Inspecting File Metadata and Path Attributes

Learners will use Path methods to verify file existence, distinguish between files and directories, and retrieve essential system metadata.

In this lesson, you will learn how to verify the existence of files and inspect their system properties using pathlib objects.

When working with file systems, it is not enough to simply assume a path exists. Before attempting to open or process a file, we must verify its status. The pathlib module provides intuitive methods that allow us to ask a Path object questions about its current state on your hard drive.

Checking Existence and Type

The most common tasks are checking if a file exists and determining if a path refers to a file or a folder (directory). We use the .exists(), .is_file(), and .is_dir() methods for this purpose:

from pathlib import Path

data_path = Path("reports/january.csv")

if data_path.exists():
    if data_path.is_file():
        print("Confirmed: This is a file ready for processing.")
    elif data_path.is_dir():
        print("This path points to a directory, not a file.")
else:
    print("The path does not exist on this system.")

Retrieving Metadata

Beyond existence, you may need to know specific attributes about the file, such as its size or when it was last modified. The .stat() method returns an object containing this metadata. By accessing properties like st_size (in bytes) or st_mtime (the modification timestamp), you can make informed decisions in your program:

# Get file metadata
file_stats = data_path.stat()

print(f"File size: {file_stats.st_size} bytes")
print(f"Last modified: {file_stats.st_mtime}")

Why This Matters

Using these inspection methods is a cornerstone of the EAFP (Easier to Ask for Forgiveness than Permission) and LBYL (Look Before You Leap) design patterns. While you might use try-except blocks to handle unexpected issues, checking metadata first prevents your program from attempting operations on non-existent or invalid targets. This proactive approach leads to cleaner, more predictable file handling in your scripts.

Key Takeaway: Always verify a path’s existence and type using exists(), is_file(), or is_dir() before performing file I/O operations to prevent runtime errors.