sanitize-filename is a simple, dependency-free, blacklist-based filename sanitizer for Python. It focuses on preserving the original filename as much as possible, including non-ASCII characters, while removing characters unsafe for common file systems. The current version is 1.2.0, released in April 2020. It's a stable library with infrequent updates, primarily for minor fixes and behavior uniformity.
pip install sanitize-filenameVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to import and use the `sanitize` function to clean up a filename string, removing characters that are typically invalid or problematic across various file systems.
For maximum security, consider supplementing with additional validation or using a whitelist approach if applicable to your use case.
Implement additional logic to ensure uniqueness for file storage, such as appending a timestamp or a hash to the filename before saving.
Upgrade to version 1.2.0 or higher to ensure consistent cross-platform behavior and handle edge cases with dot-only filenames.
Always separate the path from the filename. Sanitize only the filename component, and validate/construct the directory path independently to prevent directory traversal attacks (e.g., using `os.path.basename` and `os.path.join`).
Add a check after sanitization: `sanitized_name = sanitize(input_name); if not sanitized_name: sanitized_name = 'untitled'`. Provide a sensible default filename if the sanitized output is empty.
No dependency data recorded yet.