How to Sanitize Filenames in Python
Strip illegal filename characters and clean up names for safe filesystem use.
Python code
37 linesimport re
from pathlib import Path
def sanitize_filename(filename: str, replacement: str = "_") -> str:
"""
Remove illegal characters from a filename.
Illegal characters: / \\ : * ? " < > |
Also strips leading/trailing spaces and dots.
"""
# Remove illegal characters
sanitized = re.sub(r'[\\/:*?"<>|]', replacement, filename)
# Strip leading/trailing whitespace and dots
sanitized = sanitized.strip(" .")
# Prevent empty filename
if not sanitized:
sanitized = "unnamed"
return sanitized
if __name__ == "__main__":
# Test cases
test_filenames = [
"my:file?.txt",
"data/report*2022",
" photo (1).jpg ",
"invalid|name:<test>",
"...",
"normal-file.txt"
]
for name in test_filenames:
result = sanitize_filename(name)
print(f"'{name}' -> '{result}'")
Output
'my:file?.txt' -> 'my_file_.txt'
'data/report*2022' -> 'data_report_2022'
' photo (1).jpg ' -> 'photo (1).jpg'
'invalid|name:<test>' -> 'invalid_name__test_'
'...' -> 'unnamed'
'normal-file.txt' -> 'normal-file.txt'
How it works
The regex [\\/:*?"<>|] matches every illegal character in one pass and swaps each with the replacement. Calling strip(" .") removes leading and trailing spaces and dots so names don't end up hidden or malformed. If everything gets stripped away, the fallback "unnamed" guarantees a valid filename. This approach is pure standard library code — no third-party packages needed.
Common mistakes
- Forgetting that filenames can't end with dots or spaces on some filesystems, which `strip()` handles
- Not considering reserved Windows device names like CON, NUL, or PRN
- Using a single regex that replaces illegal characters but leaves empty names
Variations
- Use `unicodedata.normalize` to also remove non-ASCII characters before sanitizing
- Add checks for reserved names on Windows (CON, PRN, AUX, NUL, etc.)
Real-world use cases
- Cleaning user-uploaded file names before saving them to cloud storage or S3 buckets.
- Normalizing filenames in batch ETL pipelines that pull data from inconsistent external sources.
- Creating safe reporting or export filenames from arbitrary strings like dates and metadata.
Sponsored
More from Files & data
- Append a Line to a Log File in Python easy
- Audit File Permissions Across a Project in Python easy
- Automatically Detect Corrupted Files Using SHA-256 Checksums in Python easy
- Automatically Highlight Data Validation Errors Inside Excel Files in Python easy
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a File Index by Relative Path Hash Map in Python easy
Keep learning
Related tutorials and quizzes for this topic.