C

Python › Module 1 › Lesson 3

BeginnerModule 1Lesson 3/5

File Handling

Read and write log files and wordlists safely with Python’s open(), paths, and context managers

15 min+53 XP3 quiz
Module progress3 of 5
321
open() · Logs · Reports

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

1

Why use with open(...) as f:?

Multiple choice

Knowledge Check

2

True or False: Security scripts often read logs line by line.

True or False

Knowledge Check

3

open(path, "w") means:

Multiple choice

← Previous

Answer all 3 knowledge checks to continue. (0/3 answered)