Unit 7 — Input and Output — Reading and Writing Network Data
Reading Text Files
Most real network data starts as a file — a device list, a config export, a log. Python reads files with open():
with open("devices.txt") as f:
for line in f:
print(line.strip())
with ensures the file closes automatically when the block ends. strip() removes the newline at the end of each line.
To read the whole file at once:
with open("devices.txt") as f:
content = f.read()
To read into a list of lines:
with open("devices.txt") as f:
lines = f.readlines()
Writing Files
Open with "w" to write (creates the file if it does not exist, overwrites if it does). Open with "a" to append:
with open("report.txt", "w") as f:
f.write("Device Status Report\n")
f.write("=" * 25 + "\n")
f.write("sw-core-01 — online\n")
Combine reading and writing to transform data:
with open("devices.txt") as infile, open("report.txt", "w") as outfile:
for i, line in enumerate(infile, start=1):
outfile.write(f"{i:2}. {line.strip()}\n")
Formatted Output with f-strings
You have used f-strings already. A few more tools:
Alignment and padding:
name = "sw-core-01"
status = "online"
print(f"{name:<20} {status}")
# sw-core-01 online
:<20 left-aligns and pads to 20 characters. :>20 right-aligns. :^20 centres.
Number formatting:
accuracy = 0.9375
print(f"Accuracy: {accuracy:.1%}")
# Accuracy: 93.8%
count = 1234567
print(f"Packets: {count:,}")
# Packets: 1,234,567
JSON — The Format Every Network API Uses
JSON is what network APIs return. Python's json module reads and writes it.
Save a list of device dicts to a file:
import json
devices = [
{"name": "sw-core-01", "ip": "10.1.1.1", "site": "HQ"},
{"name": "rtr-edge-01", "ip": "10.1.1.254", "site": "HQ"},
]
with open("devices.json", "w") as f:
json.dump(devices, f, indent=2)
Load it back:
with open("devices.json") as f:
devices = json.load(f)
for d in devices:
print(d["name"], "—", d["ip"])
json.dump() writes to a file. json.dumps() returns a string. json.load() reads from a file. json.loads() parses a string.
Summary
open("file")reads,open("file", "w")writes,open("file", "a")appends- Always use
with— it closes the file automatically f.read()= whole file as string,f.readlines()= list of lines,for line in f= one line at a timestrip()removes trailing newlines when reading line by linejson.dump()writes JSON to a file,json.load()reads it back- f-string padding:
{value:<20}left-align,{value:>20}right-align