withopen("config.txt","r", encoding="utf-8")as f:
content = f.read()print(content[:50])# Read line by line (memory efficient)withopen("data.log")as f:for line in f:print(line.strip())
Note Always specify encoding='utf-8' explicitly. The default varies by platform. Iterating line-by-line avoids loading the entire file into memory.
Note Always pass newline='' when opening CSV files (the csv module handles line endings itself). DictReader/DictWriter are more readable than plain reader/writer.
Note json.dump/load work with file objects. json.dumps/loads work with strings. Use indent= for readable output. Python dicts serialize directly to JSON objects.
from contextlib import contextmanager
@contextmanager
deftemp_directory():import tempfile, shutil
path = tempfile.mkdtemp()try:yield path
finally:
shutil.rmtree(path)withtemp_directory()as tmp:print(f"Working in {tmp}")
Note The with statement guarantees cleanup code runs even if an exception occurs. Use contextlib.contextmanager to build custom context managers from generators.
from pathlib importPath# All Python files in current directoryfor py_file inPath(".").glob("*.py"):print(py_file.name)# Recursive search
all_json =list(Path(".").rglob("*.json"))print(f"Found {len(all_json)} JSON files")
Note glob() searches one level. rglob() searches recursively through all subdirectories. Both return Path objects.