Pathvalidate

3.3.1 · active · verified Sun Mar 29

pathvalidate is a Python library to sanitize/validate a string such as filenames/file-paths/etc. It provides functions to remove invalid characters, replace reserved names, and normalize paths for various operating systems (Linux, Windows, macOS, POSIX, universal). The current version is 3.3.1, and it maintains an active release cadence with regular updates and feature enhancements.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to validate a filename, and how to sanitize both filenames and file paths, handling potential `ValidationError` exceptions.

import sys
from pathvalidate import ValidationError, validate_filename, sanitize_filename, sanitize_filepath

# Example 1: Validate a filename
try:
    validate_filename("my:file*name?.txt")
    print("Filename is valid.")
except ValidationError as e:
    print(f"Validation error: {e}", file=sys.stderr)

# Example 2: Sanitize a filename
invalid_fname = "my:inval|id*file?.txt"
sanitized_fname = sanitize_filename(invalid_fname)
print(f"Sanitized filename '{invalid_fname}' -> '{sanitized_fname}'")

# Example 3: Sanitize a filepath
invalid_fpath = "/usr/loc:al/my<dir>/invalid?file.log"
sanitized_fpath = sanitize_filepath(invalid_fpath)
print(f"Sanitized filepath '{invalid_fpath}' -> '{sanitized_fpath}'")

view raw JSON →