← How-To Guides How-To How to sanitize a filename Remove or replace unsafe characters. Use re.sub(r'[\/:*?"<>|]', '_', s) or a whitelist of allowed chars. Safe chars Avoid path traversal and invalid chars. import re safe = re.sub(r"[\/:*?"<>|]", "_", name)