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
Copy
from pathlib import Path
path = Path("/home/user/documents")
print(path) # Output: /home/user/documents2. Checking If a Path Exists
Copy
from pathlib import Path
path = Path("example.txt")
print(path.exists()) # Output: True or False3. Creating a Directory
Copy
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
Copy
5. Filtering Files by Extension
Copy
6. Reading a File
Copy
7. Writing to a File
Copy
8. Getting File Metadata
Copy
9. Getting File Name and Parent Directory
Copy
10. Renaming or Moving a File
Copy
Last updated