Skip to content

Instantly share code, notes, and snippets.

@yeiichi
Created July 6, 2025 01:40
Show Gist options
  • Save yeiichi/d3d2f974eff0dd0855ce784cf79d9f33 to your computer and use it in GitHub Desktop.
Save yeiichi/d3d2f974eff0dd0855ce784cf79d9f33 to your computer and use it in GitHub Desktop.
Sanitize a string to make it safe for use as a filename
import re
# macOS/Windows compatibility
INVALID_FILENAME_CHARS = re.compile(r'[<>:"/\\|?*\x00-\x1F]|[\s.]$')
def sanitize_filename(filename: str) -> str:
"""
Sanitizes a string to make it safe for use as a filename.
Replaces problematic characters with a hyphen (-).
"""
return INVALID_FILENAME_CHARS.sub('-', filename)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment