Tutorpip← About this lessonOpen the sheet →Download PDF
Ages 10+ · Coding · Variables and data
Data from a file
Open the fileRead a rowUse the rowClose the file
A program reads a file row by row.
The big ideaA file keeps data after a program stops. A program reads it row by row.

How it works

A variable forgets when the program stops. A file is saved on the computer, so it is still there tomorrow.

Think of a file as a folder full of rows. Each row is one line of data, like Monday and one thousand steps.

A program opens the file, reads a row and uses it. It repeats this for every row, starting from the top, and then closes the file.

If a row has a mistake, the chart will show it.

Keeps its data• a file on the computer• a saved table of rowsForgets it• a variable• a number held in memory
What keeps data and what forgets it.

Example 1: Why a file

  1. Zoe types Monday's steps into a variable, and the program stops.
  2. Next morning the variable is empty and Monday's steps are gone.
  3. A file keeps its rows, so a file would still have them.

Example 2: Reading the rows

  1. The file has a row for each day: Monday 1000 steps, Tuesday 1200, Wednesday 10000, Thursday 1100 and Friday 900.
  2. The program reads one row at a time, from the top.
  3. Each row makes one bar in the chart.

Example 3: A tall bar

  1. Wednesday's bar is taller than the whole screen.
  2. Its row says ten thousand steps, far more than the other days.
  3. Bo walked a normal loop, so the row has an extra zero.
  4. The fix: change the row to 1000, and the chart looks normal.

Example 4: The steps of the program

  1. Open the file.
  2. Read a row, and use it. Do that again for every row.
  3. Close the file, so everything stays safe and tidy.

Words to know

file
Saved on the computer, so it keeps its data after the program stops.
row
One line of data in a file, like a day and its steps.
variable
A box that keeps a value only while the program runs.

Watch out

Try it

  1. Which keeps its data after the program stops, a file or a variable?
  2. A program reads a file one what at a time?
  3. What is the last step of reading a file?
  4. A chart has one bar far taller than the rest. Where do you look?
  5. Monday has 1000 steps and Friday has 900. Which is fewer?
Answers: 1. A file · 2. One row · 3. Close the file · 4. At that bar's row in the file · 5. Friday
Try at homeEach night for a week, write one row in a notebook: the day, and one number, like how many pages you read. The notebook is your file, and it remembers. At the end of the week, read it row by row and draw a bar for each day. Does any row look odd?
For grown-upsDo the notebook Mission: write one row a night for a week, the day and one number, then read it row by row at the end and draw a bar for each day. Does any row look odd?
Open these notes on screenScan the code, or go to tutorpip.com.