📊 We use cookies & analytics to improve your experience. Learn more
Latest

Python for Absolute Beginners Module 4 · Lesson 10 of 15

0% Exit to course

Module 4 · Files and real data Lesson 10 of 15

Reading and writing files

Learning objective

with open("data.txt") as f: reads a file and closes it for you, even if the code inside fails — which is why `with` is the pattern to learn first.

The concept

with open("data.txt") as f: opens a file and closes it for you, even if the code inside fails — which is why with is the pattern to learn first and not a shorthand to upgrade to later. Then for line in f: walks it one line at a time, which is how large files are read without loading all of them into memory at once.

Writing takes a mode: open("report.txt", "w") replaces the file, while "a" appends to it. That difference has wiped out more data than any other beginner line of code — use "a" when you are adding today's entry to yesterday's. Each line you write ends with \n, and each line you read arrives with one, which is why line.strip() appears in almost every file loop.

Python
with open("notes.txt", "a") as f:      # "a" appends; "w" would wipe the file
    print("Learned functions today", file=f)

with open("notes.txt") as f:
    for line in f:
        print(line.strip())

Common mistakes

The mistake is a path that is not where you think it is. data.txt means "in the folder the program was started from", not "next to my script" — use an absolute path while learning, and get in the habit of opening the file in your editor to confirm the write actually happened.

Worked example

for line in f: print(line.strip()) — strip() removes the newline character that would otherwise print a blank line between every row.

Your practice task

Write a program that writes three lines to a file and then reads them back, printing the count of lines.

Do this before moving on. Reading a solution teaches the shape of it; typing it teaches you.

Key takeaway

with open("data.txt") as f: opens a file and closes it for you, even if the code inside fails — which is why with is the pattern to learn first and not a shorthand to upgrade to later.

Create free account or sign in

Almost there

15 lessons left of 15

Finish every lesson to unlock the certificate. Each one ends in a practice task — do them and the final project brief writes itself.