Pathvalidate
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
- breaking Dropped support for Python 3.7 and 3.8 in v3.2.2. Prior to that, v3.1.0 dropped Python 3.6 support. Users on older Python versions must upgrade to Python 3.9 or newer to use current versions of pathvalidate.
- breaking The return type of `ValidationError.reason` changed from `Optional[ErrorReason]` to `ErrorReason` in v3.1.0. Code expecting an `Optional` type for this attribute may need adjustments.
- breaking In v3.0.0, the `min_len` argument was removed from the constructors of `FileNameSanitizer` and `FilePathSanitizer`, and a `validator` argument was added. Additionally, `InvalidLengthError` was removed, with `ValidationError` now used for length-related issues.
- gotcha For platform-specific validation or sanitization, you must explicitly specify the `platform` argument (e.g., 'Windows', 'Linux', 'macOS', 'POSIX') in functions like `validate_filename` or `sanitize_filename`. If omitted, it defaults to 'universal' (most restrictive) for filenames or 'auto' for file paths, which might not match your intended target environment's rules.
- deprecated Version 2.5.1 introduced `DeprecationWarning` for some functions. While specific functions are not detailed in release notes, users should pay attention to warnings during execution or linting.
Install
-
pip install pathvalidate
Imports
- validate_filename
from pathvalidate import validate_filename
- sanitize_filename
from pathvalidate import sanitize_filename
- ValidationError
from pathvalidate import ValidationError
- sanitize_filepath
from pathvalidate import sanitize_filepath
Quickstart
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}'")