Python's pathlib Module ๐Ÿ“

Folder path icon

Python's pathlib Module ๐Ÿ“

The pathlib module enables handling filesystem paths in an object-oriented manner, providing intuitive and OS-independent path manipulations.

1. Basic Usage and Creating a Path Object

from pathlib import Path

p = Path('my_folder') / 'subfolder' / 'example.txt'
print(p)  # my_folder/subfolder/example.txt
print(p.exists())  # False (checks existence)

2. Creating Directories and Reading/Writing Files

folder = Path('logs')
folder.mkdir(exist_ok=True)

file = folder / 'app.log'
file.write_text("Application log\n", encoding='utf-8')
print(file.read_text(encoding='utf-8'))

3. Getting File Information

print(file.name)       # app.log
print(file.stem)       # app
print(file.suffix)     # .log
print(file.parent)     # logs
print(file.stat().st_size, "bytes")

4. Iterating Over Directory Contents

for child in folder.iterdir():
    print(child.name, "-", "Directory" if child.is_dir() else "File")

Summary

  • Use Path objects for safe and intuitive path handling.
  • Easily perform file and directory operations like mkdir, write_text, and read_text.
  • Simplify file metadata retrieval and directory traversal.

Comments

Popular posts from this blog

Mastering Python Generators and yield: Efficient Iteration Explained

Mastering Python Sets: Remove Duplicates and Do More

Python Logging Module: Basics and Best Practices ๐Ÿ“