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 4 · Core

Bad rows, missing files and safe handling

Check for a missing file, skip and report bad rows, compare counts and protect the original.

  • 50 minutes
  • Serves O6
  • Assumes M6.L3

Phase 1: Prepare

Step 1 Warm-up recall

From M6.L3: why must you convert a CSV field before adding it?

Private: nothing you type here is sent or stored.

Step 2 Learning goal

By the end of this lesson you can:

  • check for a missing file (Foundation);
  • skip and report bad rows (Core);
  • protect the original data (Core).

Phase 2: Teach

Step 3 A familiar example

An accountant never writes on the original receipts. She copies the figures, checks the count and keeps the originals safe. A careful program does the same with data files.

Step 4 Clear explanation

Real files have problems: the file may not exist, a row may be blank, a score may be text. A careful program checks, reports and never overwrites the original.

import os

good = 0
bad = 0
total = 0
if not os.path.exists("scores.txt"):
    print("File not found")
else:
    with open("scores.txt") as f:
        for line in f:
            parts = line.strip().split(",")
            if len(parts) == 2 and parts[1].isdigit():
                total = total + int(parts[1])
                good = good + 1
            else:
                bad = bad + 1
    print(good, bad, total)
2 1 155
Fileexists?Rowsvalid?Countsin = out?Writea new file
Check every step: the file exists, every row is valid, the count out matches the count in, and the original is never overwritten.

Three habits protect the data. First, check each row before using it: the right number of parts, and a field that really is a number. Second, compare counts: rows read should equal rows used plus rows skipped, and the program should report the skipped ones instead of hiding them. Third, write to a new file and keep the original. A backup is only useful if it has been tested by restoring from it at least once.

Step 5 Worked example (4 marks)

A file has four lines: Ann,70, Bo,x, an empty line and Cy,60. Using the code above, give good, bad and total.

  1. Ann,70 is valid: good 1, total 70. (1 mark)
  2. Bo,x fails isdigit and the empty line has one part: bad 2. (1 mark)
  3. Cy,60 is valid: good 2, total 130. (1 mark)
  4. Answer: 2, 2 and 130. (1 mark)

Go deeper: the professor's notes

A fix that only hides a problem should be written down with its assumption.
Fix

What it does.

Assumes

Write it.

Test

Edges.

Problemdata formatFixwindow or convertRecordassumptionTestedges
Quick fix

Fixes

FixLasts
window the yearuntil the window ends
four-digit yearpermanently

At work: A date window

Two-digit years are mapped to a range.

  1. State the window.
  2. Test the end of the range.

What a careful practitioner decides. Document what a quick fix assumes.

Phase 3: Practise

Step 6 Learner practice (instant-marked)

1. A good program, on finding a bad row, should:

2. The count check is:

3. os.path.exists("a.txt") tells you:

4. A backup is trustworthy when:

Phase 4: Close

Step 7 Recap

  • Check the file and each row.
  • Compare counts in and out, and report skipped rows.
  • Write to a new file and test your backups.

Step 8 Exit ticket (ungraded)

List three checks a program should make before it writes a result file.

Private: nothing you type here is sent or stored.

Step 9 Go further (Extension)

Add a count of skipped rows and their line numbers to a file-reading program.

In industry: Fixed by a window

Peter de Jager, an early campaigner on Y2K, said in a later interview that the problem was solved largely by windowing, which treats two-digit years as if they were four-digit ones, rather than by removing it.

Link to this lesson. A quick fix in the reading step can hide a data-format problem rather than cure it; record what the fix assumes.

Source: Computerworld, Have we learned nothing from Y2K?

Common mistakes

MistakeWhy it fails
Skipping bad rows silentlyReport how many and which.
Writing over the originalUse a new file name.
Never testing a backupRestore once to prove it works.

Limits. Error handling with try and except is covered in Module 7.

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 · How do you deal with a bad row?
Testeach rowSkipand countReportthem
Bad rows

Test it before use: the right number of parts and a field that really is a number. Skip it, count it and report it; do not hide it.

Card 2 of 3 · Why compare counts in and out?
Read10Used8Skipped2
Counts

Rows read should equal rows used plus rows skipped. If they differ, some rows have gone missing and the result cannot be trusted.

Card 3 of 3 · What makes a backup trustworthy?
Makea copyRestoreas a testThentrust it
Backup

A restore that you have actually carried out. A backup that has never been restored may be empty, old or unreadable.

Review with flashcards

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

Open the module flashcards