A permissive filename sanitizer.
Actively maintained. Last release 2 weeks ago. A safe choice.
pip install sanitize-filenameA simple, dependency-free, blacklist-based filename sanitizer, for when you want to keep the original filename.
Note that a blacklist based sanitizer will never be as safe as a whitelist based one. In most cases, your best option is to create a safe filename yourself. Your second safest option is to use a whitelist approach (allowing only certain characters). This sanitizer is useful when you want to keep the original filename, including non ascii characters, whenever possible. It might be useful for trusted but dirty input, but should not be used with raw user input!
Installation
pip install sanitize_filename
Usage
from sanitize_filename import sanitize
filename = input("Enter a file name:")
filename = sanitize(filename)
Examples:
> sanitize("A/B/C.txt")
'ABC.txt'
> sanitize("this𓀦filenameḜisあactually...valid.txt")
'this𓀦filenameḜisあactually...valid.txt'
> sanitize("def.")
'def'
> sanitize("NUL")
'__NUL'
> sanitize("..")
'__'
> sanitize("x" * 200 + ".txt", max_bytes=10)
'xxxxxx.txt'
Arguments to sanitize
max_bytessets the maximum number of UTF-8 bytes. Default is 255.
Changelog
-
1.3.0
- Add
max_bytesargument tosanitize() - Filenames are now NFC normalized rather than NFKD, so that e.g. narrow non-break space (common in macOS screenshot names) are kept.
- Count UTF-8 bytes, not characters, when limiting filename length. This will make long non-ascii filenames shorter than in earlier versions.
- Blacklist bidi control chars, to avoid e.g. "file\u202etxt.exe" displaying locally as "fileexe.txt"
- Make sure the result of truncating a filename can not be a reserved word (e.g.
CON [...] x.txt) - Limit filename extensions to 16 characters, and truncate separately
- Make sure not to split character sequences when truncating names
- Do all character removals in one step to speed up execution
- Add
-
1.2.1
- Fix a bug where a fullwidth character could be used craft path traversal attack
- Add some missing Windows device names
- Remove lone surrogates
- Fix a bug where names could be crafted to end in a dot.
- Remove C1 range control characters