Python Session 02: File Operations

Working with files. This session covers reading, writing, JSON parsing, CSV handling, and pathlib.

Pre-Session State

  • Understand lists and dicts

  • Can use comprehensions

  • Know f-string formatting

Setup

# Create test files
echo -e "line1\nline2\nline3" > /tmp/test.txt

cat > /tmp/hosts.json << 'EOF'
[
  {"name": "kvm-01", "ip": "10.50.1.110"},
  {"name": "kvm-02", "ip": "10.50.1.111"}
]
EOF

cat > /tmp/hosts.csv << 'EOF'
name,ip,vlan
kvm-01,10.50.1.110,10
kvm-02,10.50.1.111,10
EOF

Lesson 1: Reading Files

Concept: Use with open() for safe file handling.

Exercise 1.1: Read entire file

with open('/tmp/test.txt', 'r') as f:
    content = f.read()
    print(content)

Exercise 1.2: Read lines

with open('/tmp/test.txt', 'r') as f:
    lines = f.readlines()
    print(lines)  # Includes \n

# Strip newlines
with open('/tmp/test.txt', 'r') as f:
    lines = [line.strip() for line in f]
    print(lines)

Exercise 1.3: Iterate lines

with open('/tmp/test.txt', 'r') as f:
    for line in f:
        print(f"Line: {line.strip()}")

Lesson 2: Writing Files

Concept: Mode 'w' overwrites, 'a' appends.

Exercise 2.1: Write file

hosts = ["kvm-01", "kvm-02", "vault-01"]
with open('/tmp/output.txt', 'w') as f:
    for host in hosts:
        f.write(f"{host}\n")

Exercise 2.2: Append to file

with open('/tmp/output.txt', 'a') as f:
    f.write("ise-01\n")

Exercise 2.3: Write multiple lines

lines = ["line1", "line2", "line3"]
with open('/tmp/output.txt', 'w') as f:
    f.writelines(line + '\n' for line in lines)

Lesson 3: JSON Files

Concept: Use json module for JSON serialization.

Exercise 3.1: Read JSON

import json

with open('/tmp/hosts.json', 'r') as f:
    hosts = json.load(f)

for host in hosts:
    print(f"{host['name']}: {host['ip']}")

Exercise 3.2: Write JSON

import json

data = [
    {"name": "vault-01", "ip": "10.50.1.60"},
    {"name": "vault-02", "ip": "10.50.1.61"}
]

with open('/tmp/vault.json', 'w') as f:
    json.dump(data, f, indent=2)

Exercise 3.3: JSON string conversion

import json

data = {"name": "kvm-01", "active": True}
json_str = json.dumps(data)
print(json_str)

parsed = json.loads(json_str)
print(parsed["name"])

Lesson 4: CSV Files

Concept: Use csv module for CSV handling.

Exercise 4.1: Read CSV as dicts

import csv

with open('/tmp/hosts.csv', 'r') as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(f"{row['name']}: {row['ip']}")

Exercise 4.2: Write CSV

import csv

hosts = [
    {"name": "kvm-01", "ip": "10.50.1.110", "vlan": 10},
    {"name": "kvm-02", "ip": "10.50.1.111", "vlan": 10}
]

with open('/tmp/output.csv', 'w', newline='') as f:
    writer = csv.DictWriter(f, fieldnames=["name", "ip", "vlan"])
    writer.writeheader()
    writer.writerows(hosts)

Lesson 5: Pathlib

Concept: Object-oriented filesystem paths.

Exercise 5.1: Path operations

from pathlib import Path

p = Path('/tmp/hosts.json')
print(p.exists())
print(p.name)
print(p.suffix)
print(p.parent)

Exercise 5.2: Glob files

from pathlib import Path

for f in Path('/tmp').glob('*.json'):
    print(f.name)

Exercise 5.3: Read/write with pathlib

from pathlib import Path

p = Path('/tmp/test.txt')
content = p.read_text()
p.write_text("new content")

Summary: What You Learned

Concept Syntax Example

Read file

with open(f, 'r') as f:

f.read(), f.readlines()

Write file

with open(f, 'w') as f:

f.write(str)

JSON load

json.load(f)

From file handle

JSON dump

json.dump(data, f)

To file handle

CSV read

csv.DictReader(f)

Iterate rows as dicts

CSV write

csv.DictWriter(f, fields)

writer.writerows(data)

Pathlib

Path('/path')

.exists(), .glob(), .read_text()

Exercises to Complete

  1. [ ] Read /etc/hosts and print non-comment lines

  2. [ ] Parse hosts.json and write as CSV

  3. [ ] Find all .adoc files in a directory using pathlib

  4. [ ] Append timestamp to a log file

Next Session

Session 03: Strings - Methods, f-strings, regex.

Session Log

Timestamp Notes

Start

<Record when you started>

End

<Record when you finished>