156. File Handling with pathlib
Here are 10 Python snippets demonstrating file handling with the pathlib module for object-oriented file system path manipulation. Each snippet is separated by a delimiter.
Snippet 1: Create a Path Object
Copy
from pathlib import Path
path = Path('/home/user/documents')
print("Path:", path)Snippet 2: Check If a File Exists
Copy
from pathlib import Path
file_path = Path('example.txt')
if file_path.exists():
print(f"{file_path} exists.")
else:
print(f"{file_path} does not exist.")Snippet 3: Create a Directory
Copy
Snippet 4: Write to a File
Copy
Snippet 5: Read from a File
Copy
Snippet 6: Iterating Over Files in a Directory
Copy
Snippet 7: Get File Extension
Copy
Snippet 8: Rename a File
Copy
Snippet 9: Delete a File
Copy
Snippet 10: Resolve Absolute Path
Copy
Last updated