How to Sanitize Filenames in Python

Strip illegal filename characters and clean up names for safe filesystem use.

Easy Python 3.9+ Aug 9, 2026 Files & data 12 views 0 copies

Python code

37 lines
Python 3.9+
import 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

stdout
'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

  1. Use `unicodedata.normalize` to also remove non-ASCII characters before sanitizing
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Files & data

Related tutorials and quizzes for this topic.