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.
pip install pathvalidateVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to validate a filename, and how to sanitize both filenames and file paths, handling potential `ValidationError` exceptions.
Upgrade your Python environment to version 3.9 or higher.
Update type hints and logic to directly handle `ErrorReason` as the return type for `ValidationError.reason`.
Review calls to `FileNameSanitizer` and `FilePathSanitizer` constructors, remove `min_len`, and consider using the new `validator` argument if needed. Catch `ValidationError` instead of `InvalidLengthError`.
Always pass the `platform` argument (e.g., `platform='Windows'`) to validation and sanitization functions if specific OS rules are required.
Check `DeprecationWarning` messages during development and update to the recommended alternative functions or methods.
Install the package using pip: `pip install pathvalidate`
Use `sanitize_filename()` or `sanitize_filepath()` to remove or replace invalid characters before validation, or ensure the input string contains only valid characters.
```python
from pathvalidate import validate_filename, sanitize_filename, ValidationError
try:
validate_filename('fi:l*e/p"a?t>h|.t<xt')
except ValidationError as e:
print(e) # Output: [PV1100] invalid characters found: ...
# Fix:
sanitized_name = sanitize_filename('fi:l*e/p"a?t>h|.t<xt')
print(sanitized_name) # Output: filepath.txt
validate_filename(sanitized_name) # This will now pass
```Use `sanitize_filename()` or `sanitize_filepath()` which automatically handles reserved names by default, or provide a different name. You can also specify a `reserved_name_handler` for custom behavior.
```python
from pathvalidate import validate_filename, sanitize_filename, ValidationError
try:
validate_filename('COM1', platform='Windows')
except ValidationError as e:
print(e) # Output: [PV1002] found a reserved name by a platform: 'COM1'
# Fix:
sanitized_name = sanitize_filename('COM1', platform='Windows')
print(sanitized_name) # Output: _COM1
validate_filename(sanitized_name, platform='Windows') # This will now pass
```Correct the spelling of the function name to `sanitize_filename` (using 'z').
```python
# Wrong:
# from pathvalidate import sanitise_filename
# Correct:
from pathvalidate import sanitize_filename
filename = 'my/file.txt'
sanitized = sanitize_filename(filename)
print(f'{filename} -> {sanitized}')
```No dependency data recorded yet.