>[!quote] In a Nutshell >Introduced with [[- Python Programming Language -|Python]] 3.4, more flexible and object-oriented module to handle filesystem paths compared to the older `os.path`. >- **Object-Oriented Design** - based on a `Path` class that overloads operators like `/` >- **Cross-Platform Compatibility** - automatically handles differences between different operating systems >- **File and Directory Operations** - built-in functions for filesystem operations such as checking for existence, i/o and iterating through directories ![[Pasted image 20250120154016.png|center|400]] .... --- #### Basic Usage | **Operation** | **Code Example** | **Description** | | -------------------------------------- | --------------------------------------------- | -------------------------------------------------------- | | **Creating a Path Object** | `p = Path("/home/user/docs")` | Creates a `Path` object representing a filesystem path. | | **Joining Paths** | `p2 = p / "file.txt"` | Uses the `/` operator to join paths. | | **Parent Directory** | `parent = p2.parent` | Retrieves the parent directory of the path. | | **File Name** | `file_name = p2.name` | Retrieves the file name (last part of the path). | | **Stem (File Name without Extension)** | `stem = p2.stem` | Retrieves the file name without its extension. | | **File Extension (Suffix)** | `suffix = p2.suffix` | Retrieves the file extension (e.g., `.txt`). | | **Check if Path is a File** | `p2.is_file()` | Checks if the path points to a file. | | **Check if Path is a Directory** | `p.is_dir()` | Checks if the path points to a directory. | | **Iterating over Directory** | `for file in p.iterdir(): ...` | Iterates over the contents of a directory. | | **Resolving a Path to Absolute** | `absolute_path = p.resolve()` | Resolves a relative path to an absolute one. | | **Comparing Paths** | `p1 == p2` | Compares two `Path` objects for equality. | | **Reading File Content** | `content = p.read_text()` | Reads the text content of a file. | | ------------------------ | --------------------------------------------- | -------------------------------------------------------- | | **Writing to a File** | `p.write_text("Hello, world!")` | Writes text to a file. | | **Creating Directories** | `dir_path.mkdir(parents=True, exist_ok=True)` | Creates a directory, and optionally creates parent dirs. |