Lesson 10: File Input/Output – Reading & Writing Data

1. Why Work with Files?

Real ML datasets come from files (CSV, JSON, images).

Basic modes:

Use with statement — auto-closes file.

Exercise 1

What does this do?
with open("data.txt", "w") as f:
    f.write("Hello ML!")

2. Reading Files

with open("data.txt", "r") as f:
    content = f.read()
    print(content)

# Or read line by line
with open("data.txt", "r") as f:
    for line in f:
        print(line.strip())

Common: read CSV for ML datasets.

Exercise 2

After this code runs, what is inside "log.txt"?

with open("log.txt", "w") as f:
    f.write("Epoch 1: Loss 0.5\n")
    f.write("Epoch 2: Loss 0.3")
# Answer:

Exercise 3

Which are safe ways to read a file?
← Previous Lesson (9) Next Lesson (11) →