Files & data
Read and write files safely; parse JSON, CSV, and common text formats.
How to Detect File Encoding: UTF-8 vs Latin-1 in Python
Detect whether a file is UTF-8 or Latin-1 encoded by attempting a UTF-8 decode and falling back to Latin-1.
import sys
def detect_encoding(file_path):
with open(file_path, 'rb') as f:
raw = f.read()
try:
raw.decode('utf-8')
return 'UTF-8'
except UnicodeDecodeError:
return 'latin1'
if __name__ == "__main__":
file_path = sys.argv[1] if len(sys.argv) > 1 else 'sample.txt'
…
How to Read a JSON File into a Dictionary in Python
Load a JSON file into a Python dictionary using the json.load() function with proper file handling and UTF-8 encoding.
import json
from pathlib import Path
def read_json_file(filepath: str) -> dict:
"""Read a JSON file and return its contents as a dictionary."""
path = Path(filepath)
with path.open("r", encoding="utf-8") as f:
data = json.load(f)
return data
if __name__ == "__main__":
# Create a sample JS…
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.
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")
…
How to Transcode a File from Latin-1 to UTF-8 in Python
Read a latin1-encoded text file and rewrite it as UTF-8 using Python's pathlib and encoding parameters.
from pathlib import Path
def transcode_to_utf8(input_path, output_path):
"""Read a latin1-encoded file and write it as UTF-8."""
source = Path(input_path)
target = Path(output_path)
with source.open(encoding='latin1') as infile:
content = infile.read()
with target.open('w', encod…
Read Entire File into String with read Method in Python
Open a file, read its entire content into a string using the .read() method, and clean up with a context manager.
from pathlib import Path
def read_file_to_string(file_path: str) -> str:
"""Read the entire file content into a string using the read method."""
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
return content
if __name__ == "__main__":
# Create a temporary file for d…
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.