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

from pathlib import Path

path = Path('/home/user/documents')
print("Path:", path)

Snippet 2: Check If a File Exists

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

from pathlib import Path

directory = Path('new_directory')
directory.mkdir(exist_ok=True)
print(f"Directory '{directory}' created.")

Snippet 4: Write to a File


Snippet 5: Read from a File


Snippet 6: Iterating Over Files in a Directory


Snippet 7: Get File Extension


Snippet 8: Rename a File


Snippet 9: Delete a File


Snippet 10: Resolve Absolute Path


Last updated