Python Strings, Files, and Exceptions

String handling, file I/O, pathlib, JSON, and exception-handling patterns.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all
## Strings
f-string interpolation
message = f"Hello, {name}!"

# f-string interpolation

Format number with commas
label = f"{total:,}"

# Format number with commas

Split and strip
parts = [part.strip() for part in csv_line.split(",")]

# Split and strip

Join strings
path = "/".join(["api", "v1", "users"])

# Join strings

Replace text
cleaned = text.replace("\t", "    ")

# Replace text

Prefix / suffix checks
if filename.endswith(".py") and filename.startswith("test_"):
    print("test file")

# Prefix / suffix checks

Strip whitespace
normalized = line.strip()

# Strip whitespace

## Files and paths
Read a text file
with open("notes.txt", "r", encoding="utf-8") as f:
    text = f.read()

# Read a text file

Read line by line
with open("app.log", "r", encoding="utf-8") as f:
    for line in f:
        print(line.rstrip())

# Read line by line

Write a text file
with open("output.txt", "w", encoding="utf-8") as f:
    f.write("hello
")

# Write a text file

Append to a file
with open("events.log", "a", encoding="utf-8") as f:
    f.write("started
")

# Append to a file

Use pathlib
from pathlib import Path
path = Path("src") / "main.py"
exists = path.exists()

# Use pathlib

Read JSON from disk
import json
from pathlib import Path
data = json.loads(Path("config.json").read_text(encoding="utf-8"))

# Read JSON from disk

## Exceptions
Basic try / except
try:
    value = int(user_input)
except ValueError:
    value = 0

# Basic try / except

Catch multiple exceptions
try:
    data = json.loads(payload)
except (TypeError, ValueError) as exc:
    print(exc)

# Catch multiple exceptions

Else and finally
try:
    result = risky()
except Exception as exc:
    logger.error(exc)
else:
    print(result)
finally:
    cleanup()

# Else and finally

Raise custom error
raise ValueError("expected a positive integer")

# Raise custom error

Exception chaining
try:
    parse_config(path)
except OSError as exc:
    raise RuntimeError("config load failed") from exc

# Exception chaining

Define custom exception
class ConfigError(Exception):
    pass

# Define custom exception