Python › Module 1 › Lesson 3
File Handling
Read and write log files and wordlists safely with Python’s open(), paths, and context managers
Opening
Your first “sensor” is often a text file
Auth logs, DNS logs, web access logs—defenders live in files. Python’s open() with a context manager (with) reads them line by line without forgetting to close the handle.
1. Read a File Safely
Read lines from a logpath = "auth.log" with open(path, "r", encoding="utf-8", errors="ignore") as f: for line in f: print(line.strip())
path = "auth.log"
with open(path, "r", encoding="utf-8", errors="ignore") as f:
for line in f:
print(line.strip())2. Write Results
Write findings to a reportfindings = ["failed login from 10.0.0.5", "failed login from 10.0.0.8"] with open("report.txt", "w", encoding="utf-8") as out: for item in findings: out.write(item + "\ ")
findings = ["failed login from 10.0.0.5", "failed login from 10.0.0.8"]
with open("report.txt", "w", encoding="utf-8") as out:
for item in findings:
out.write(item + "\
")3. Security Notes
Validate paths in real tools so users cannot escape directories (path traversal). For this course, keep sample files in your project folder. Use encoding="utf-8" and errors="ignore" when logs contain messy bytes.
with open(...) as f:
Prefer context managers. They close files even if your script crashes mid-loop.
Knowledge Check
Why use with open(...) as f:?
Multiple choice
Knowledge Check
True or False: Security scripts often read logs line by line.
True or False
Knowledge Check
open(path, "w") means:
Multiple choice