Reading Files Safely with `open()` and `with`
Always open files using `with open(path, "r", encoding="utf-8") as f:`. Read full content with `.read()`, or iterate line by line to protect memory.
# Streaming one line at a time (RAM-friendly):
# with open("server.log", "r", encoding="utf-8") as f:
# for line in f:
# print(line.strip())
print("Line-by-line streaming keeps RAM usage near zero.")
# 15. Reading Files Safely with `open()` and `with` Always open files using `with open(path, "r", encoding="utf-8") as f:`. Read full content with `.read()`, or iterate line by line to protect memory: ```python # Streaming one line at a time (RAM-friendly): # with open("server.log", "r", encoding="utf-8") as f: # for line in f: # print(line.strip()) print("Line-by-line streaming keeps RAM usage near zero.") ``` Always pass `encoding="utf-8"`. If omitted, Python defaults to the OS system encoding (which is legacy `cp1252` on many Windows machines), causing random `UnicodeDecodeError` crashes on international characters.