Python22 min read

Python Pathlib

Work with files and folders using pathlib: paths, checks, creation, reading, writing, and cross-platform handling.

Michael Brown
July 29, 2025
12.1k475

pathlib gives an object-oriented way to work with file paths. It replaces old os.path style and is more readable.

    ## Creating paths
    
    ```python
    from pathlib import Path
    
    print(Path.cwd())
    print(Path.home())
    
    path = Path("data/files/info.txt")
    print(path)
    ```
    
    ## Path properties
    
    ```python
    path = Path("data/files/report.txt")
    
    print(path.name)
    print(path.stem)
    print(path.suffix)
    print(path.parent)
    ```
    
    ## Checking paths
    
    ```python
    print(path.exists())
    print(path.is_file())
    print(path.is_dir())
    ```
    
    ## Create directories
    
    ```python
    Path("new_folder").mkdir(exist_ok=True)
    Path("data/reports/2025").mkdir(parents=True, exist_ok=True)
    ```
    
    ## Listing files
    
    ```python
    folder = Path("data")
    
    for f in folder.iterdir():
        print(f)
    
    for f in folder.glob("*.txt"):
        print(f)
    ```
    
    ## Reading and writing
    
    ```python
    path = Path("example.txt")
    
    path.write_text("Hello Python!")
    print(path.read_text())
    ```
    
    ## Joining paths
    
    ```python
    base = Path("data")
    file = base / "reports" / "2025" / "jan.txt"
    print(file)
    ```
    
    ## Graph: pathlib usage
    
    ```mermaid
    flowchart LR
      A[Path object] --> B[Check exists]
      A --> C[Create dirs]
      A --> D[Read/Write]
      A --> E[Join paths]
    ```
    
    ## Key points
    
    - Cleaner than os.path
    - Cross-platform
    - Use / to join paths
    - Path objects have many helpers
    
    In the next lesson, you will move into async and await, opening the door to high-performance I/O programs.
#Python#Intermediate#Files