API Reference

Complete API reference for pathlib3.

Path Class

class pathlib3.Path(*args, **kwargs)[source]

Bases: PosixPath

Extended Path class with 40+ additional utility methods. Inherits ALL functionality from pathlib.Path and adds more.

All original pathlib.Path methods are available: - .exists(), .is_file(), .is_dir(), .is_symlink() - .stat(), .chmod(), .rename(), .replace() - .mkdir(), .rmdir(), .unlink(), .touch() - .read_text(), .read_bytes(), .write_text(), .write_bytes() - .glob(), .rglob(), .iterdir() - .resolve(), .absolute(), .relative_to() - .with_name(), .with_suffix(), .with_stem() - .parent, .parents, .name, .stem, .suffix, .suffixes - .anchor, .parts, .drive, .root - .as_posix(), .as_uri() - .expanduser(), .home(), .cwd() - .match(), .is_relative_to(), .is_absolute() - .joinpath(), .samefile() - and many more…

Additional method categories:

BASIC UTILITIES: - .ext() - Get extension without dot - .basename() - Get filename with extension - .base() - Get filename without extension - .dirname() - Get directory path as string - .abspath() - Get absolute path as string

NONE HANDLING: - Path(None) - Creates Path(‘.’) instead of error - .safe() - Class method to create Path safely from optional - .from_optional() - Class method to create Path or return None

PATH MANIPULATION: - .normpath() - Normalize path - .join() - Join path components - .split_ext() - Split into base and extension - .split_path() - Split path into components - .change_ext() - Change file extension

DIRECTORY OPERATIONS: - .ensure_dir() - Create directory if doesn’t exist - .ensure_parent() - Create parent directory - .touch_parent() - Create parent dirs and touch file - .ls() - List directory contents - .tree() - Show directory tree - .find() - Find files recursively

FILE OPERATIONS: - .rm() - Remove file or directory - .copy_to() - Copy file to destination - .move_to() - Move file to destination - .append_text() - Append text to file - .append_bytes() - Append bytes to file - .backup() - Create backup of file

FILE INFO: - .size() - Get file size - .size_human() - Get human-readable size - .mtime() - Get modification time - .ctime() - Get creation time - .atime() - Get access time - .age() - Get file age in seconds - .is_empty() - Check if empty - .is_newer_than() - Compare modification times - .is_older_than() - Compare modification times

CONTENT OPERATIONS: - .lines() - Read lines as list - .read_json() - Read JSON file - .write_json() - Write JSON file - .read_pickle() - Read pickle file - .write_pickle() - Write pickle file - .hash() - Calculate file hash - .checksum() - Alias for hash - .count_lines() - Count lines in file - .validate() - Validate file format - .metadata() - Extract file metadata (images, PDFs, audio, video, docs) - .metadata_simple() - Get simple metadata summary

SEARCH & FILTER: - .find_files() - Find files by pattern - .find_dirs() - Find directories by pattern - .walk() - Walk directory tree

MUSIC TAGS: - .music_tag() - Get music tag - .show_info() - Display music tags

COMPARISON: - .same_content() - Check if files have same content

EMAIL OPERATIONS: - .email_as_attachment() - Send file as email attachment - .send_email() - Send email with multiple attachments (static method)

IMAGE OPERATIONS (requires Pillow): - .to_ico() - Convert image to ICO format (single or multi-size) - .resize() - Resize image with aspect ratio preservation - .thumbnail() - Create thumbnail - .convert_format() - Convert image format (PNG, JPEG, WebP, etc.) - .metadata() - Extract image metadata (EXIF, dimensions, etc.)

static __new__(cls, *args, **kwargs)[source]

Create new Path instance with None handling.

abspath() str[source]

Get absolute path as string.

Returns:

Absolute path

Return type:

str

Example

>>> Path('file.txt').abspath()
'/current/working/dir/file.txt'
age() float[source]

Get file age in seconds since last modification.

Returns:

Age in seconds

Return type:

float

Example

>>> Path('file.txt').age()
3600.5
append_bytes(data: bytes) Path[source]

Append bytes to file.

Parameters:

data – Bytes to append

Returns:

self (for chaining)

Return type:

Path

Example

>>> Path('data.bin').append_bytes(b'\x00\x01\x02')
append_text(text: str, encoding: str = 'utf-8', newline: bool = False) Path[source]

Append text to file.

Parameters:
  • text – Text to append

  • encoding – Text encoding (default: ‘utf-8’)

  • newline – Add newline before text

Returns:

self (for chaining)

Return type:

Path

Example

>>> Path('log.txt').append_text('New log entry')
atime() float[source]

Get access time as timestamp.

Returns:

Access timestamp

Return type:

float

Example

>>> Path('file.txt').atime()
1704067200.0
backup(suffix: str = '.bak') Path[source]

Create backup of file.

Parameters:

suffix – Backup suffix (default: ‘.bak’)

Returns:

Backup file path

Return type:

Path

Example

>>> Path('important.txt').backup()
Path('important.txt.bak')
base() str[source]

Get the base name without extension. Alias for .stem property.

Returns:

Filename without extension (e.g., ‘file’)

Return type:

str

Example

>>> Path('file.txt').base()
'file'
basename() str[source]

Get the base name (filename with extension). Alias for .name property.

Returns:

Basename (e.g., ‘file.txt’)

Return type:

str

Example

>>> Path('/home/user/file.txt').basename()
'file.txt'
change_ext(new_ext: str) Path[source]

Change file extension.

Parameters:

new_ext – New extension (with or without dot)

Returns:

Path with new extension

Return type:

Path

Example

>>> Path('file.txt').change_ext('md')
Path('file.md')
>>> Path('file.txt').change_ext('.json')
Path('file.json')
checksum(algorithm: str = 'sha256') str[source]

Alias for hash().

Parameters:

algorithm – Hash algorithm (default: ‘sha256’)

Returns:

Hexadecimal hash

Return type:

str

Example

>>> Path('file.txt').checksum()
'a591a6d40bf420404a011733cfb7b190d62c65bf0bcda32b57b277d9ad9f146e'
convert_format(target_format: str, output_path: str | Path | None = None, quality: int = 95, **kwargs) Path[source]

Convert image to different format.

Parameters:
  • target_format – Target format (‘png’, ‘jpg’, ‘jpeg’, ‘webp’, ‘bmp’, ‘gif’)

  • output_path – Output path (default: same name with new extension)

  • quality – Quality for lossy formats (1-100)

  • **kwargs – Additional format-specific arguments

Returns:

Converted file path

Return type:

Path

Example

>>> # PNG to JPEG
>>> Path('image.png').convert_format('jpg')
Path('image.jpg')
>>> # JPEG to WebP (smaller size)
>>> Path('photo.jpg').convert_format('webp', quality=80)
Path('photo.webp')
>>> # Any format to PNG (lossless)
>>> Path('image.bmp').convert_format('png')
Path('image.png')
copy_to(dest: str | Path | Path, overwrite: bool = False) Path[source]

Copy file or directory to destination.

Parameters:
  • dest – Destination path

  • overwrite – Overwrite if exists

Returns:

Destination path

Return type:

Path

Example

>>> Path('source.txt').copy_to('dest.txt')
Path('dest.txt')
count_lines(encoding: str = 'utf-8') int[source]

Count lines in file.

Parameters:

encoding – Text encoding (default: ‘utf-8’)

Returns:

Number of lines

Return type:

int

Example

>>> Path('file.txt').count_lines()
42
create_table() None[source]

Create a Rich Table for displaying music tags. :returns: Rich Table object or None if Rich is not available :rtype: Table

ctime() float[source]

Get creation/metadata change time as timestamp.

Returns:

Creation timestamp

Return type:

float

Example

>>> Path('file.txt').ctime()
1704067200.0
dirname() str[source]

Get the directory name as string.

Returns:

Directory path

Return type:

str

Example

>>> Path('/home/user/file.txt').dirname()
'/home/user'
email_as_attachment(to: str | List[str], subject: str, body: str = '', config: EmailConfig | None = None, from_addr: str | None = None, cc: str | List[str] | None = None, bcc: str | List[str] | None = None, body_html: str | None = None, attachment_name: str | None = None, inline_images: bool = False) bool[source]

Send this file as email attachment.

Parameters:
  • to – Recipient email(s)

  • subject – Email subject

  • body – Email body (plain text)

  • config – EmailConfig instance with SMTP settings

  • from_addr – Sender email (if None, uses config.username)

  • cc – CC recipients

  • bcc – BCC recipients

  • body_html – HTML body (optional, overrides plain body)

  • attachment_name – Custom attachment filename (default: file’s name)

  • inline_images – Embed images inline (for image files only)

Returns:

True if sent successfully

Return type:

bool

Raises:

Example

>>> config = EmailConfig.gmail('me@gmail.com', 'app_password')
>>> Path('report.pdf').email_as_attachment(
...     to='boss@company.com',
...     subject='Monthly Report',
...     body='Please find attached report.',
...     config=config
... )
True
>>> # Multiple recipients
>>> Path('invoice.pdf').email_as_attachment(
...     to=['client@company.com', 'manager@company.com'],
...     subject='Invoice #12345',
...     body='Invoice attached.',
...     cc='accounting@company.com',
...     config=config
... )
ensure_dir(mode: int = 511) Path[source]

Create directory if it doesn’t exist (for directories).

Parameters:

mode – Directory permissions (default: 0o777)

Returns:

self (for chaining)

Return type:

Path

Example

>>> Path('/tmp/new_folder').ensure_dir()
Path('/tmp/new_folder')
ensure_parent(mode: int = 511) Path[source]

Create parent directory if it doesn’t exist.

Parameters:

mode – Directory permissions (default: 0o777)

Returns:

self (for chaining)

Return type:

Path

Example

>>> Path('/tmp/new_folder/file.txt').ensure_parent()
Path('/tmp/new_folder/file.txt')
ext() str[source]

Get file extension without the dot.

Returns:

File extension (e.g., ‘txt’, ‘py’, ‘tar.gz’)

Return type:

str

Example

>>> Path('file.txt').ext()
'txt'
>>> Path('archive.tar.gz').ext()
'gz'
find(pattern: str = '*', recursive: bool = True) List[Path][source]

Find files matching pattern.

Parameters:
  • pattern – Glob pattern

  • recursive – Search recursively

Returns:

List of matching Path objects

Return type:

list

Example

>>> Path('/tmp').find('*.txt')
[Path('/tmp/file1.txt'), Path('/tmp/sub/file2.txt')]
find_dirs(pattern: str = '*') List[Path][source]

Find directories matching pattern recursively.

Parameters:

pattern – Glob pattern

Returns:

List of matching directory paths

Return type:

list

Example

>>> Path('/tmp').find_dirs('test*')
[Path('/tmp/test1'), Path('/tmp/sub/test2')]
find_files(pattern: str = '*') List[Path][source]

Find files matching pattern recursively.

Parameters:

pattern – Glob pattern

Returns:

List of matching file paths

Return type:

list

Example

>>> Path('/tmp').find_files('*.txt')
[Path('/tmp/file1.txt'), Path('/tmp/sub/file2.txt')]
classmethod from_optional(path: str | Path | Path | None) Path | None[source]

Create Path from optional value, returns None if input is None.

Parameters:

path – Path string or Path object (can be None)

Returns:

Path instance or None

Return type:

Path or None

Example

>>> Path.from_optional(None)
None
>>> Path.from_optional("file.txt")
Path('file.txt')
hash(algorithm: str = 'sha256', chunk_size: int = 8192) str[source]

Calculate file hash.

Parameters:
  • algorithm – Hash algorithm (md5, sha1, sha256, etc.)

  • chunk_size – Size of chunks to read (default: 8192 bytes)

Returns:

Hexadecimal hash

Return type:

str

Example

>>> Path('file.txt').hash()
'a591a6d40bf420404a011733cfb7b190d62c65bf0bcda32b57b277d9ad9f146e'
is_empty() bool[source]

Check if file or directory is empty.

Returns:

True if empty, False otherwise

Return type:

bool

Example

>>> Path('empty.txt').is_empty()
True
is_newer_than(other: str | Path | Path) bool[source]

Check if this file is newer than another.

Parameters:

other – Other file path

Returns:

True if this file is newer

Return type:

bool

Example

>>> Path('new.txt').is_newer_than('old.txt')
True
is_older_than(other: str | Path | Path) bool[source]

Check if this file is older than another.

Parameters:

other – Other file path

Returns:

True if this file is older

Return type:

bool

Example

>>> Path('old.txt').is_older_than('new.txt')
True
join(*args) Path[source]

Join path components.

Parameters:

*args – Path components to join

Returns:

Joined path

Return type:

Path

Example

>>> Path('/home').join('user', 'documents', 'file.txt')
Path('/home/user/documents/file.txt')
lines(encoding: str = 'utf-8', strip: bool = True, skip_empty: bool = False) List[str][source]

Read file lines as list.

Parameters:
  • encoding – Text encoding (default: ‘utf-8’)

  • strip – Strip whitespace from lines

  • skip_empty – Skip empty lines

Returns:

List of lines

Return type:

list

Example

>>> Path('file.txt').lines()
['line 1', 'line 2', 'line 3']
ls(pattern: str = '*', only_files: bool = False, only_dirs: bool = False) List[Path][source]

List directory contents as Path objects.

Parameters:
  • pattern – Glob pattern (default: “*”)

  • only_files – Only return files

  • only_dirs – Only return directories

Returns:

List of Path objects

Return type:

list

Example

>>> Path('/tmp').ls()
[Path('/tmp/file1.txt'), Path('/tmp/file2.txt')]
>>> Path('/tmp').ls('*.txt')
[Path('/tmp/file1.txt'), Path('/tmp/file2.txt')]
>>> Path('/tmp').ls(only_files=True)
[Path('/tmp/file1.txt')]
metadata(include_basic: bool = True, raw: bool = False) dict[source]

Extract metadata from various file types.

Supports: Images (JPEG, PNG, etc.), PDF, Audio (MP3, FLAC, etc.),

Video (MP4, MKV, etc.), Office docs (DOCX, XLSX, PPTX)

Parameters:
  • include_basic – Include basic file info (size, dates, permissions)

  • raw – Return raw metadata without processing (file-type specific)

Returns:

Metadata dictionary with file information

Return type:

dict

Raises:
  • ImportError – If required library is not installed

  • ValueError – If file type is not supported or file doesn’t exist

Example

>>> Path('photo.jpg').metadata()
{
    'file_type': 'image',
    'format': 'JPEG',
    'size': 2048576,
    'size_human': '2.0 MB',
    'width': 1920,
    'height': 1080,
    'created': 1704067200.0,
    'modified': 1704067200.0,
    'exif': {...}
}
>>> Path('document.pdf').metadata()
{
    'file_type': 'pdf',
    'pages': 10,
    'author': 'John Doe',
    'title': 'Report',
    ...
}
Supported formats and required libraries:
  • Images (JPEG, PNG, GIF, BMP, TIFF): Pillow (pip install Pillow)

  • PDF: PyPDF2 (pip install PyPDF2)

  • Audio/Video (MP3, MP4, FLAC, etc.): mutagen (pip install mutagen)

  • Word (DOCX): python-docx (pip install python-docx)

  • Excel (XLSX): openpyxl (pip install openpyxl)

metadata_simple() str[source]

Get simple human-readable metadata summary.

Returns:

Formatted metadata string

Return type:

str

Example

>>> print(Path('photo.jpg').metadata_simple())
File: photo.jpg
Type: image (JPEG)
Size: 2.0 MB
Dimensions: 1920x1080
Created: 2024-01-01 10:00:00
move_to(dest: str | Path | Path) Path[source]

Move file or directory to destination.

Parameters:

dest – Destination path

Returns:

Destination path

Return type:

Path

Example

>>> Path('old.txt').move_to('new.txt')
Path('new.txt')
mtime() float[source]

Get modification time as timestamp.

Returns:

Modification timestamp

Return type:

float

Example

>>> Path('file.txt').mtime()
1704067200.0
music_tag(exts: List | None = ['mp3', 'mp4', 'm4a', 'flac', 'ogg', 'wav', 'wma', 'aac']) dict | None[source]

Get music file tags (requires ‘mutagen’ package).

Returns:

Music tags or None if not a music file or mutagen not installed

Return type:

dict

Example

>>> Path('song.mp3').music_tag()
{'title': 'Song Title', 'artist': 'Artist Name'}
normpath() Path[source]

Normalize path (remove redundant separators and up-level references).

Returns:

Normalized path

Return type:

Path

Example

>>> Path('/home//user/../user/file.txt').normpath()
Path('/home/user/file.txt')
read_json(encoding: str = 'utf-8', **kwargs) Any[source]

Read JSON file.

Parameters:
  • encoding – Text encoding (default: ‘utf-8’)

  • **kwargs – Additional arguments for json.load()

Returns:

Parsed JSON data

Example

>>> Path('config.json').read_json()
{'key': 'value'}
read_pickle() Any[source]

Read pickle file.

Returns:

Unpickled data

Example

>>> Path('data.pkl').read_pickle()
{'key': 'value'}
resize(width: int | None = None, height: int | None = None, max_size: int | None = None, keep_aspect: bool = True, output_path: str | Path | None = None, quality: int = 95, optimize: bool = True) Path[source]

Resize image with aspect ratio preservation.

Parameters:
  • width – Target width (None = auto from height)

  • height – Target height (None = auto from width)

  • max_size – Maximum dimension (scales to fit)

  • keep_aspect – Preserve aspect ratio

  • output_path – Output path (default: overwrite original)

  • quality – JPEG quality 1-100 (default: 95)

  • optimize – Optimize output file size

Returns:

Output file path

Return type:

Path

Raises:

Example

>>> # Resize to specific width (auto height)
>>> Path('image.jpg').resize(width=800)
>>> # Resize to fit in 1024x1024
>>> Path('photo.png').resize(max_size=1024)
>>> # Exact size (no aspect ratio)
>>> Path('banner.jpg').resize(
...     width=1200,
...     height=400,
...     keep_aspect=False
... )
>>> # Save to different file
>>> Path('original.png').resize(
...     width=500,
...     output_path='thumbnail.png'
... )
rm(recursive: bool = False, missing_ok: bool = False) None[source]

Remove file or directory.

Parameters:
  • recursive – If True, remove directory recursively

  • missing_ok – If True, don’t raise error if path doesn’t exist

Example

>>> Path('file.txt').rm()
>>> Path('folder').rm(recursive=True)
classmethod safe(path: str | Path | Path | None, default: str = '.') Path[source]

Create Path safely, handling None values. More explicit alternative to Path(None).

Parameters:
  • path – Path string or Path object (can be None)

  • default – Default path if input is None (default: ‘.’)

Returns:

Path instance

Return type:

Path

Example

>>> Path.safe(None)
Path('.')
>>> Path.safe(None, '/tmp')
Path('/tmp')
>>> Path.safe("file.txt")
Path('file.txt')
same_content(other: str | Path | Path, chunk_size: int = 8192) bool[source]

Check if two files have the same content.

Parameters:
  • other – Other file path

  • chunk_size – Size of chunks for comparison (default: 8192)

Returns:

True if contents are identical

Return type:

bool

Example

>>> Path('file1.txt').same_content('file2.txt')
False
static send_email(to: str | List[str], subject: str, body: str, config: EmailConfig, from_addr: str | None = None, cc: str | List[str] | None = None, bcc: str | List[str] | None = None, body_html: str | None = None, attachments: List[str | Path] | None = None) bool[source]

Send email with optional multiple attachments.

Parameters:
  • to – Recipient email(s)

  • subject – Email subject

  • body – Email body (plain text)

  • config – EmailConfig instance

  • from_addr – Sender email

  • cc – CC recipients

  • bcc – BCC recipients

  • body_html – HTML body

  • attachments – List of file paths to attach

Returns:

True if sent successfully

Return type:

bool

Example

>>> config = EmailConfig.gmail('me@gmail.com', 'password')
>>> Path.send_email(
...     to='boss@company.com',
...     subject='Weekly Report',
...     body='See attached files.',
...     config=config,
...     attachments=['report.pdf', 'chart.png']
... )
show_info(table: None = None, exts: List | None = ['mp3', 'mp4', 'm4a', 'flac', 'ogg', 'wav', 'wma', 'aac'], no_rich=False) None[source]

Show music file tags (requires ‘mutagen’ package).

Parameters:
  • table – Rich Table object to populate (if None, a new one is created)

  • exts – List of file extensions to consider as music files

Returns:

None

Example

>>> Path('song.mp3').show_info()
>>> Path('music_dir').show_info()
size() int[source]

Get file size in bytes. For directories, returns total size.

Returns:

Size in bytes

Return type:

int

Example

>>> Path('file.txt').size()
1024
size_human() str[source]

Get human-readable file size.

Returns:

Human-readable size (e.g., ‘1.5 MB’)

Return type:

str

Example

>>> Path('file.txt').size_human()
'1.0 KB'
split_ext() Tuple[str, str][source]

Split path into base and extension.

Returns:

(base_path, extension)

Return type:

tuple

Example

>>> Path('/home/user/file.txt').split_ext()
('/home/user/file', '.txt')
split_path() List[str][source]

Split path into list of components.

Returns:

List of path components

Return type:

list

Example

>>> Path('/home/user/file.txt').split_path()
['/', 'home', 'user', 'file.txt']
thumbnail(size: int = 256, output_path: str | Path | None = None, suffix: str = '_thumb', square: bool = False) Path[source]

Create thumbnail from image.

Parameters:
  • size – Maximum dimension (default: 256)

  • output_path – Output path (default: add suffix to filename)

  • suffix – Filename suffix (default: ‘_thumb’)

  • square – Make square thumbnail with padding

Returns:

Thumbnail file path

Return type:

Path

Example

>>> Path('photo.jpg').thumbnail()
Path('photo_thumb.jpg')
>>> Path('image.png').thumbnail(size=128, square=True)
Path('image_thumb.png')
to_ico(sizes: List[int] | None = None, output_path: str | Path | None = None, multi_size: bool = False, overwrite: bool = False) Path | List[Path][source]

Convert image (PNG, JPEG, etc.) to ICO format.

Parameters:
  • sizes – List of icon sizes (default: [16, 32, 48, 64, 128, 256])

  • output_path – Output path (default: same name with .ico extension)

  • multi_size – Create one multi-size ICO file (default: separate files)

  • overwrite – Overwrite existing files

Returns:

Created ICO file(s)

Return type:

Path or List[Path]

Raises:

Example

>>> # Single image to multiple ICO files
>>> Path('logo.png').to_ico()
[Path('logo_16.ico'), Path('logo_32.ico'), ...]
>>> # Custom sizes
>>> Path('icon.png').to_ico(sizes=[16, 32, 64])
>>> # Multi-size ICO (Windows style)
>>> Path('app.png').to_ico(multi_size=True)
Path('app.ico')
>>> # Custom output path
>>> Path('image.jpg').to_ico(
...     output_path='favicon.ico',
...     multi_size=True
... )
touch_parent() Path[source]

Create parent directories and touch file.

Returns:

self (for chaining)

Return type:

Path

Example

>>> Path('/tmp/new_folder/file.txt').touch_parent()
Path('/tmp/new_folder/file.txt')
tree(max_depth: int | None = None, prefix: str = '') str[source]

Generate directory tree structure as string.

Parameters:
  • max_depth – Maximum depth to traverse

  • prefix – Prefix for formatting (internal use)

Returns:

Tree structure

Return type:

str

Example

>>> print(Path('/tmp').tree(max_depth=2))
/tmp
├── file1.txt
├── folder1/
│   ├── file2.txt
│   └── file3.txt
validate(file_type: str | None = None, strict: bool = True) Tuple[bool, str | None][source]

Validate file format (JSON, YAML, TOML, INI).

Parameters:
  • file_type – File type to validate (‘json’, ‘yaml’, ‘yml’, ‘toml’, ‘ini’) If None, auto-detect from extension

  • strict – If True, raise error for missing libraries. If False, return (False, error_msg)

Returns:

(is_valid, error_message)

(True, None) if valid (False, “error message”) if invalid

Return type:

tuple

Raises:
  • ImportError – If required library is not installed (when strict=True)

  • ValueError – If file type is not supported

Example

>>> Path('config.json').validate()
(True, None)
>>> Path('config.yaml').validate()
(False, "PyYAML library not installed. Install with: pip install pyyaml")
>>> is_valid, error = Path('config.toml').validate(strict=False)
>>> if not is_valid:
...     print(f"Invalid: {error}")
Supported formats:
  • JSON (built-in, always available)

  • YAML (requires PyYAML: pip install pyyaml)

  • TOML (built-in Python 3.11+, or requires tomli: pip install tomli)

  • INI (built-in, always available)

walk() Iterator[Tuple[Path, List[str], List[str]]][source]

Walk directory tree (similar to os.walk).

Yields:

tuple – (dirpath, dirnames, filenames)

Example

>>> for dirpath, dirs, files in Path('/tmp').walk():
...     print(f"Directory: {dirpath}")
...     print(f"Subdirs: {dirs}")
...     print(f"Files: {files}")
write_json(data: Any, encoding: str = 'utf-8', indent: int = 2, ensure_ascii: bool = False, **kwargs) Path[source]

Write data as JSON file.

Parameters:
  • data – Data to write

  • encoding – Text encoding (default: ‘utf-8’)

  • indent – JSON indentation (default: 2)

  • ensure_ascii – Ensure ASCII encoding (default: False)

  • **kwargs – Additional arguments for json.dump()

Returns:

self (for chaining)

Return type:

Path

Example

>>> Path('config.json').write_json({'key': 'value'})
write_pickle(data: Any, protocol: int = 5) Path[source]

Write data as pickle file.

Parameters:
  • data – Data to pickle

  • protocol – Pickle protocol version

Returns:

self (for chaining)

Return type:

Path

Example

>>> Path('data.pkl').write_pickle({'key': 'value'})

PurePath3 Class

class pathlib3.PurePath3(*args)[source]

Bases: PurePath

Extended PurePath with additional utility methods (no I/O operations)

base() str[source]

Get the base name without extension

basename() str[source]

Get the base name (filename with extension)

change_ext(new_ext: str) PurePath3[source]

Change file extension

dirname() str[source]

Get the directory name as string

ext() str[source]

Get file extension without the dot

join(*args) PurePath3[source]

Join path components

split_ext() Tuple[str, str][source]

Split path into base and extension

split_path() List[str][source]

Split path into list of components

Method Categories

Basic Utilities

Methods for getting basic path information:

  • ext() - Get extension without dot

  • basename() - Get filename with extension

  • base() - Get filename without extension

  • dirname() - Get directory path

  • abspath() - Get absolute path as string

Path Manipulation

Methods for manipulating paths:

  • normpath() - Normalize path

  • join(*args) - Join path components

  • split_ext() - Split into base and extension

  • split_path() - Split into components list

  • change_ext(new_ext) - Change file extension

Directory Operations

Methods for working with directories:

  • ensure_dir() - Create directory if doesn’t exist

  • ensure_parent() - Create parent directory

  • touch_parent() - Create parent dirs and touch file

  • ls(pattern, only_files, only_dirs) - List contents

  • tree(max_depth) - Display directory tree

  • find(pattern, recursive) - Find files matching pattern

File Operations

Methods for file manipulation:

  • rm(recursive, missing_ok) - Remove file/directory

  • copy_to(dest, overwrite) - Copy to destination

  • move_to(dest) - Move to destination

  • append_text(text) - Append text to file

  • append_bytes(data) - Append bytes to file

  • backup(suffix) - Create backup copy

File Information

Methods for getting file information:

  • size() - Get size in bytes

  • size_human() - Get human-readable size

  • mtime() - Get modification time

  • ctime() - Get creation time

  • atime() - Get access time

  • age() - Get age in seconds

  • is_empty() - Check if empty

  • is_newer_than(other) - Compare modification times

  • is_older_than(other) - Compare modification times

Content Operations

Methods for reading/writing content:

  • lines(encoding, strip) - Read lines as list

  • read_json(encoding) - Read JSON file

  • write_json(data, indent) - Write JSON file

  • read_pickle() - Read pickle file

  • write_pickle(data) - Write pickle file

  • hash(algorithm) - Calculate file hash

  • checksum(algorithm) - Alias for hash

  • count_lines() - Count lines in file

Search & Filter

Methods for searching:

  • find_files(pattern) - Find files recursively

  • find_dirs(pattern) - Find directories recursively

  • walk() - Walk directory tree

Comparison

Methods for comparing files:

  • same_content(other) - Check if files have same content

Music File Metadata

Methods for working with music file metadata:

  • show_info() - Display music file metadata

  • show_info(exts) - Display metadata for music files in directory

  • music_tag() - Get music file metadata as dict

  • music_tag(exts) - Get metadata for music files in directory as list of dicts