LightMySky

Reading and Writing Files, Including CSV

Opening a file, reading it line by line or writing to it, and closing it again, plus the row-and-column shape of CSV. This is where a program's data starts outliving the run that produced it.

No account needed. Progress saves in this browser.

What a learner can do afterwards

  • Read a text file line by line and build a result from it
  • Write records to a CSV file and read them back into objects or dictionaries
  • Say what closing a file does, and what a relative path depends on

1 · Read

You open a file with open, which hands you a file object to work through. Then you pick how to pull text: read grabs the whole file as one string, readline grabs the next line, and readlines grabs every line as a list. When lines matter one by one, the line wise readers fit best.

Try it together

A line you read usually drags a newline character along, so you strip it before using the text. When you write lines you add the newline back yourself with write. CSV follows the same shape: rows and columns with commas splitting the columns, so one record per line.

You must close the file when done, because buffering can leave your words in memory instead of on disk. Skipping the close can leave a file empty or cut off with no error shown. Two more facts save confusion: a relative name like data.txt is resolved against where you run the program, often beside your script, and printing the file object shows its details, not its contents.

Good to know

You build results from files line by line, then write records out to CSV for the next run. Variables die when the run ends, but the saved file waits, which is how your data outlives the program that made it.

Open a handle, read or write line by line, and close so the disk keeps it.

2 · Watch

Take it off screen

Print a worksheetA4 with an answer key page for grown-ups. No screen, no internet.

Where it sits

Then practise

8 questions wait behind this lesson, each with its answer explained. Every answer feeds the sky: stars light as they are learned, and dim when it is time to come back.

Spotted a problem on this page? Tell us
Reading and Writing Files, Including CSV · Computing, ages 17 to 18 · LightMySky