Specialty Digest

Global English editionLearners’ Study Dashboard — in development
The Knowledge Library for All

Flashcards: open the module flashcards (end-of-module review with workplace questions).

Online Courses / University Track / Python from Zero

Module 6 · Lesson 1 · Core

Reading and writing text files

Open a file with with, read its lines, write a new file and choose the right mode.

  • 55 minutes
  • Serves O4
  • Assumes Module 5

Phase 1: Prepare

Step 1 Warm-up recall

From Module 5: what does a function with no return statement give back?

Private: nothing you type here is sent or stored.

Step 2 Learning goal

By the end of this lesson you can:

  • read a text file line by line (Foundation);
  • write a new file (Core);
  • choose between r, w and a (Core).

Phase 2: Teach

Step 3 A familiar example

A clerk copies figures from a ledger into a report. The ledger is only read; the report is a new sheet. A program treats files the same way: read the source, write somewhere else.

Step 4 Clear explanation

A file keeps data after the program ends. Python opens it with open, and with closes it for you when the block ends.

with open("scores.txt", "r") as f:
    for line in f:
        print(line.strip())

with open("report.txt", "w") as out:
    out.write("Done\n")
Ann,70
Bo,85
Openwith open()ReadlinesProcessloop and totalWritea new file
A program reads a file into memory, works on it, and writes the result to a new file.

Each line comes with a hidden newline at the end, so strip() removes it. The mode matters a great deal:

ModeMeaningEffect on an existing file
"r"readunchanged; error if missing
"w"writeERASED, then written
"a"appendkept; new text added at the end

Mode "w" erases an existing file the moment it is opened, before anything is written. Never open your only copy of the data for writing. Read the source, and write a different file name.

Step 5 Worked example (4 marks)

A file notes.txt holds the lines a and b. A program opens it with mode "w" and writes c. What does the file contain afterwards?

  1. Mode "w" erases the old content on opening. (1 mark)
  2. Only c is then written. (1 mark)
  3. The earlier lines a and b are lost. (1 mark)
  4. Answer: only c; mode "a" would have kept a and b. (1 mark)

Go deeper: the professor's notes

Open a file for reading to look; open a new file for writing to save. Never open your only copy with w.
r

Read.

w

Erases first.

a

Adds at end.

Openwith openModer w aWorkread or writeCloseautomatic
Modes

Modes

ModeOld content
runchanged
werased
akept

At work: A report file

You need to save results.

  1. Use a new file name.
  2. Open it with w.

What a careful practitioner decides. Write to a new file; keep the source as it was.

Phase 3: Practise

Step 6 Learner practice (instant-marked)

1. Opening an existing file with mode "w":

2. To add to the end of a file, use mode:

3. The benefit of with open(...) is:

4. A line read from a file ends with:

Phase 4: Close

Step 7 Recap

  • with open(...) opens and closes safely.
  • Lines end in a newline; strip removes it.
  • Mode w erases; mode a appends; r only reads.

Step 8 Exit ticket (ungraded)

Write the lines of data.txt to the screen, one per line, without blank gaps.

Private: nothing you type here is sent or stored.

Step 9 Go further (Extension)

Write a program that copies one file to another, adding the word COPY as the first line.

In industry: Toy Story 2 almost deleted

In 1998 a delete command removed roughly 90 percent of the files for Toy Story 2 from the studio servers. The backup system had been failing without anyone noticing. The production recovered because a supervising technical director, Galyn Susman, had a copy of the film on her home computer.

Link to this lesson. A backup that has never been restored is a hope, not a backup; test the restore.

Source: The Next Web, 21 May 2012; The Wall Street Journal as reported by Daily Wire; Kottke, 2012

Common mistakes

MistakeWhy it fails
Opening the only copy with "w"Write to a new file name.
Forgetting stripBlank lines or stray newlines appear.
Not using withThe file may stay open and unsaved.

Limits. This lesson covers plain text files; other file types such as spreadsheets use extra tools.

Flashcards for this lesson (3)

Tap a card to reveal the answer. Read the question, answer it aloud or in writing first, then check yourself against the explanation.

Card 1 of 3 · Why do programs use files?
Keepafter the endSharebetween programsReadand write
Files

A file keeps data after the program ends and lets programs share it. A sales list or a class register is read from a file, not typed again each time.

Card 2 of 3 · How do you open a file safely?
OpenwithUsef in the blockEndauto close
with open

Use with open(name) as f:. The file closes automatically at the end of the block, even if something goes wrong inside.

Card 3 of 3 · What do the modes r, w and a mean?
rreadwerasesaadds
Modes

r reads, w writes after erasing, a adds to the end. Choosing w for an existing file erases it as soon as it is opened.

Review with flashcards

Test yourself on this module with workplace flashcards and detailed answers.

Open the module flashcards