EZ LearnEZ Learn
Courses
EZ Board
Dashboard
All articles
python-for-cyber-securitypythonfile-handlingjson

File Handling

Sign the book out, do your work, sign it back in. The with statement is the librarian who makes sure the register always closes, even when a script crashes halfway.

Ashish Revar17 October 202610 min read
1 video lesson 5:19 total
Sign in to track your progress

Video lesson

A scanner needs a list of targets to read. A log analyser needs the log. A report needs somewhere to be saved. Nearly every security script talks to a file within its first ten lines, and doing it carelessly is how scripts leak resources and lose results. This article shows the safe way.

Analogy: The library register

Reading a file is like signing out a book from a library: you open the register, do your work, and sign it back in. Python's with statement is the librarian who guarantees the register is closed again even if something goes wrong partway through, which matters once a script is reading thousands of lines unattended.

with open(...)sign the book outyour code runs hereread lines, write resultsfile closedsign the book back inan error halfway? the file still closes
Figure 8.1. A with block opens the file on the way in and closes it on the way out, whether the code inside finished normally or crashed halfway.

Reading and writing

load_targets.py

# targets.txt holds one IP address per line
with open("targets.txt", "r") as f:
    targets = [line.strip() for line in f if line.strip()]

print(f"Loaded {len(targets)} targets")

# write results as JSON, one object per host
import json
with open("results.json", "w") as f:
    json.dump(host_record, f, indent=2)

The list comprehension [line.strip() for line in f if line.strip()] reads every line, removes the trailing newline, and drops blank lines, all in one pass. To run the listing as it stands, you need a targets.txt and a host_record dictionary (from the previous article). Here is a complete version you can run as is:

targets.txt

10.0.0.5
10.0.0.7

10.0.0.9
192.168.1.20

load_and_save.py

import json

with open("targets.txt", "r") as f:
    targets = [line.strip() for line in f if line.strip()]

print(f"Loaded {len(targets)} targets")
print(targets)

host_record = {"ip": "10.0.0.5", "hostname": "lab-web-01",
               "open_ports": [22, 80, 443], "os_guess": "Linux"}

with open("results.json", "w") as f:
    json.dump(host_record, f, indent=2)

print(open("results.json").read())

with open("results.json") as f:
    back = json.load(f)
print(back["open_ports"], type(back).__name__)

Sample output

Loaded 4 targets
['10.0.0.5', '10.0.0.7', '10.0.0.9', '192.168.1.20']
{
  "ip": "10.0.0.5",
  "hostname": "lab-web-01",
  "open_ports": [
    22,
    80,
    443
  ],
  "os_guess": "Linux"
}
[22, 80, 443] dict

Notice what happened to the blank line in targets.txt: it vanished, because if line.strip() is False for an empty line. The file had five lines and the script loaded four targets. json.dump wrote the dictionary out as readable JSON, and json.load read it straight back into a dictionary, which is how one script hands its results to the next.

Choosing a file mode

"r" read (text)

Loading a list of target hosts or a wordlist.

"w" write (text, overwrites)

Writing a fresh results file. Careful: it empties the file if it already exists.

"a" append (text)

Adding one line to a running log without erasing it.

"rb" read (binary)

Reading a packet capture or an image for hashing.

"wb" write (binary)

Saving a downloaded image during web mirroring.

Vocabulary: Context manager

The object a with statement manages. A file object is a context manager: entering the with block opens it, and leaving the block, whether normally or because of an error, closes it automatically. You will rely on this again in Unit 4 when opening packet captures.

Mode "a": a running log that never erases itself

Append mode is how scripts keep an activity log. Each call adds one timestamped line and leaves everything before it untouched.

scan_log.py

import datetime

def log(message, path="scan.log"):
    stamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    with open(path, "a") as f:
        f.write(f"{stamp}  {message}\n")

log("scan started")
log("10.0.0.5 port 22 open")
log("scan finished")

print(open("scan.log").read())

Sample output (your timestamps will differ)

2026-10-17 18:49:24  scan started
2026-10-17 18:49:24  10.0.0.5 port 22 open
2026-10-17 18:49:24  scan finished

Run the script twice and the log grows to six lines. Had you used mode "w", the second run would have wiped the first. Choosing between "w" and "a" is a decision about whether you want to keep history.

Mode "rb": reading bytes, and a first taste of forensics

Some files are not text at all: a packet capture, a disk image, a photograph. Binary mode ("rb") reads the raw bytes with no interpretation. Analysts use it to hash a file, producing a fixed-length fingerprint that changes if even one byte of the file changes. You will lean on this heavily in the forensics unit, when evidence must be proven untouched.

hash_a_file.py

import hashlib

def sha256_of(path):
    digest = hashlib.sha256()
    with open(path, "rb") as f:
        while chunk := f.read(8192):       # read 8 KB at a time
            digest.update(chunk)
    return digest.hexdigest()

# make a small sample file to hash
with open("evidence.bin", "wb") as f:
    f.write(b"EZ Learn evidence sample\n" * 4)

print(sha256_of("evidence.bin"))

with open("evidence.bin", "rb") as f:
    head = f.read(8)
print(head, len(head))

Sample output

4618237d344ca246ed64da6c5b07c241f88d8f5155e65697af966bf3c897d05d
b'EZ Learn' 8

Reading 8 KB at a time means a ten-gigabyte disk image can be hashed without ever holding it all in memory. The same sample file always gives the same fingerprint; change one letter and the whole fingerprint changes. The second print shows binary mode returning bytes (note the b in front of the quotes), not text.

What with saves you from

Opening a file by hand puts the closing in your hands. Forget it, or crash before reaching it, and the file stays open. A with block makes that impossible to get wrong:

with_vs_manual.py

f = open("targets.txt")
print("inside, closed?", f.closed)        # False: still open
f.close()                                  # you must remember this
print("after close(), closed?", f.closed)

with open("targets.txt") as g:
    print("inside with, closed?", g.closed)
print("after with, closed?", g.closed)     # True: closed for you

Sample output

inside, closed? False
after close(), closed? True
inside with, closed? False
after with, closed? True

When the file is not there

Scripts fail at the file more often than anywhere else, because a path is typed by a human. Ask for a wordlist that does not exist and Python raises a FileNotFoundError:

What a missing file looks like

FileNotFoundError: [Errno 2] No such file or directory: 'wordlist.txt'

You will learn to catch that error and recover from it in the exception-handling article. For now, remember that FileNotFoundError is the first thing to suspect when a script dies the moment it starts, and check the spelling and the folder you ran it from.

Case study: Scenario: the log that kept losing yesterday

A junior analyst writes a script that logs every blocked connection to blocked.log and runs it each night from a scheduler. Every morning the log holds only that night's entries, and the previous week has vanished. The script opens the file with mode "w", which truncates it on every run. Changing one character to "a" fixes it. The cost of that one wrong letter is a week of evidence nobody can recover, which is exactly why file modes are worth knowing by heart. This scenario is illustrative, but the mistake is a real and common one.

Check your understanding

Question 1: Why do security scripts use "with open(...)" rather than open() and close()?

A with block closes the file automatically, whether the code inside finishes normally or crashes. With open() and close(), an error before the close() line leaves the file open, which leaks resources and can lock the file.

Question 2: You want to add one line to a log without erasing what is already there. Which mode do you open the file in?

Mode "a" (append). Mode "w" would erase the existing contents the moment the file was opened.

Question 3: Why would you open a packet capture or an image with "rb" rather than "r"?

Those files are not text. "rb" reads the raw bytes with no decoding, which is what hashing and forensic tools need. Text mode could mangle the data or fail on bytes that are not valid text.

Key takeaway: Key takeaway

Open files with with, so they always close. Choose the mode on purpose: "r" to read, "w" to start fresh, "a" to keep history, "rb" and "wb" for raw bytes. Use json.dump and json.load to pass structured results between scripts.

Assessments

Unit Assessment

Python and Networking Foundations

20 questions30 minPass: 60%

Start exam →

Comprehensive Assessment

Python for Cyber Security: Complete Assessment

100 questions120 minPass: 60%

Start final exam →

Related to this topic

Continue learning

Reference material

Cheatsheet

Python for Cyber Security — Cheatsheet

v1.0

Open resource

MCQ Bank

Python for Cyber Security — MCQ Bank

v1.0

Open resource

Question Bank

Python for Cyber Security — Question Bank

v1.0

Open resource

eBook

Python for Cyber Security — eBook

v1.0

Open resource

Discussion

Loading comments…
More articlesTest your knowledge
EZ MentorAI · Free

File Handling

Hi! I'm EZ Mentor

Your AI tutor for
File Handling

Sign in to ask, it's free.

EZ Mentor is AI-powered · Answers may not be perfect · 10 free questions / day

EZ LearnEZ Learn

Structured learning across Reverse Engineering, Cloud Security, and Research Methodology, plus games and practice tools in EZ Arena. Free, and open to anyone.

EZ Learn

  • Courses
  • EZ Articles
  • EZ Watch
  • EZ Talks
  • EZ Bytes
  • Cyber Hygiene

EZ Library

  • All Resources
  • eBooks & PDFs
  • Question Banks
  • MCQ Banks
  • Cheatsheets

EZ Exams

  • All Exams
  • REMA
  • Cloud Security
  • Research Methodology
  • Python for Cyber Security
  • Cyber Law & IPR
  • Community
  • EZ Board

EZ Arena

  • EZ Games
  • Live Quiz
  • ML Challenges
  • दिशा - Hygiene
  • सजग - Awareness
  • अभ्यास - Practice

Platform

  • About
  • Contact
  • Terms of Use
  • Disclaimer
  • Verify Certificate
  • Events

© 2026 EZ Learn by EpochZero. Educational content for learning purposes.

Platform Lead: Ashish Revar