In Python, sanitizing a string to use as a filename involves removing or replacing any characters that are invalid or unsafe for filenames in the target operating system. Different operating systems have different restrictions on what constitutes a valid filename, but a common set of characters to avoid includes:
The null character (\0)
Forward slash (/) on Unix-like systems
Backslash (\) on Windows
Colon (:) on Windows and macOS
Asterisk (*)
Question mark (?)
Double quote (")
Less than (<)
Greater than (>)
Pipe (|)
Additionally, you might want to avoid control characters (ASCII 0-31) and whitespace characters such as spaces or tabs, as they can cause issues in certain circumstances.
Here is a simple Python function that sanitizes a string for use as a filename by replacing invalid characters with an underscore (_):
python
import re
import string
def sanitize_filename(filename):
valid_chars = f"-_.() {string.ascii_letters}{string.digits}"
sanitized = ''.join(c if c in valid_chars else '_' for c in filename)
sanitized = re.sub(r'__+', '_', sanitized) # Replace multiple underscores with one
return sanitized.strip('_') # Remove leading/trailing underscores
filename = "example:/filename?*with|illegal\"characters.txt"
safe_filename = sanitize_filename(filename)
print(safe_filename)
This function allows only alphanumeric characters, dashes, underscores, periods, parentheses, and spaces, and replaces any other characters with underscores. It also compresses multiple underscores into a single one and trims leading or trailing underscores.
Keep in mind that this is a basic example. Depending on your use case, you may need to handle additional cases such as reserved filenames (CON, PRN, AUX, NUL, etc. on Windows), maximum filename lengths, or the sanitization of entire file paths rather than just the filename component.
Also, note that using spaces and parentheses in filenames can sometimes cause issues when interacting with the filesystem from the command line or scripts, so consider avoiding them if you anticipate such interactions.