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.")
from pathlib import Path
directory = Path('.')
for file in directory.iterdir():
if file.is_file():
print("File:", file)
from pathlib import Path
file_path = Path('example.txt')
print("File Extension:", file_path.suffix)
from pathlib import Path
file_path = Path('example.txt')
new_file_path = file_path.with_name('renamed_example.txt')
file_path.rename(new_file_path)
print(f"File renamed to {new_file_path}")
from pathlib import Path
file_path = Path('renamed_example.txt')
if file_path.exists():
file_path.unlink()
print(f"{file_path} deleted.")
else:
print(f"{file_path} does not exist.")