Reference library

Files & data

Read and write files safely; parse JSON, CSV, and common text formats.

2 matches
Files & data easy

How to Sanitize Filenames in Python

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

filenames sanitize re
Python
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.su…
12 0 Open
Files & data easy

How to Strip BOM When Reading UTF-8 Files in Python

Read a UTF-8 text file with Python's pathlib while automatically stripping the Byte Order Mark (BOM) so the first character isn't a hidden glyph.

bom utf8 pathlib
Python
from pathlib import Path

def read_text_without_bom(file_path):
    """Read a UTF-8 text file, stripping the BOM if present."""
    return Path(file_path).read_text(encoding='utf-8-sig')

if __name__ == "__main__":
    # Create a sample file with BOM for demonstration
    sample_path = Path("sample_with_bom.txt")
    …
12 0 Open

Browse by section

Each section groups closely related Python snippets.

Files & data — Python code examples

What you will find here

This page collects files & data snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.

Samples vs tutorials and challenges

Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.