11. Pathlib Module
These examples cover the basics and common use cases of the pathlib module, including creating paths, managing directories and files, and reading/writing file content.
1. Creating a Path Object
from pathlib import Path
path = Path("/home/user/documents")
print(path) # Output: /home/user/documents2. Checking If a Path Exists
from pathlib import Path
path = Path("example.txt")
print(path.exists()) # Output: True or False3. Creating a Directory
from pathlib import Path
dir_path = Path("new_folder")
dir_path.mkdir(exist_ok=True)
print(f"Directory created: {dir_path}")4. Iterating Over Files in a Directory
5. Filtering Files by Extension
6. Reading a File
7. Writing to a File
8. Getting File Metadata
9. Getting File Name and Parent Directory
10. Renaming or Moving a File
Last updated