GCSE · Computer Science · Edexcel · Spec 1CP2

CSV file I/O

Your game just set a record high score. You close it. Gone. A file is how it survives.

Computer Science · Algorithms

Trace table — dry run the code

players.csv is plain text: Mia,12 then Ravi,30 then Zoe,25, one record per line. Press Next and follow one line at a time as it changes shape on its way into a 2D list.

1file = open("players.csv", "r")
2data = []
3for line in file:
4 line = line.strip()
5 line = line.split(",")
6 data.append(line)
7file.close()
8print(data[1][1])
line
data
Output
Press Start to run the first line.
·

Ready when you are — step through one line at a time.

Computer Science · Files

Which file mode does each job need?

A game keeps track of its highest scores. Data made inside a program is lost when the program closes, so the scores are saved to a file and used again next time. Pick a mode (r, w or a) for each job.

Still to sort

r (read) (0)

Get data out of an existing file.

Where the line is: r only reads. It never changes the file.

a (append) (0)

Add to the end of an existing file.

Where the line is: a keeps what is already there. w does not.

w (write) (0)

Write a file from scratch.

Where the line is: w erases any existing file with the same name before writing.

3 of 3 still to sort.

Computer Science · Files

The total that will not add up

scores.csv has one number on each line: 12, then 30, then 25. This program should print their total, but one line is wrong. Which one?

A student's program — which line goes wrong?

Computer Science · Files

Writing a 2D list back out to a CSV file

table holds Kai and 18 in one row and Ana and 21 in the next. Write it to players.csv, replacing any old file, so that each row becomes one line. Reading took strip, split and cast. Writing runs the other way, so fill in the missing steps.

  1. table = [["Kai", 18], ["Ana", 21]]A 2D list. Notice the ages are integers, not strings.
  2. missing step
Which line is step 2?

Computer Science · Files

What is a CSV file, really?

Four students are arguing about CSV files and how Python handles them.

Whose idea is closest to what you think right now?
How sure are you?

WHAT YOU'VE LEARNED

A quick recap of today's lesson.

A CSV file is just text. Learn how a program turns it into a table of values and back again.

What you need to know

  • A CSV file is plain text: one record per line, items separated by commas, so it forms rows and columns.
  • Saving data to a file lets a program use it again next time; data made inside a program is otherwise lost when it closes.
  • Have a goYour friend's game says "Highest score: 0" every single time it starts, even after a record-breaking night. Their program never saved anything to a file. Where did the record go?

    It was lost when the program closed.

    Data generated inside a program is otherwise lost when the program closes. A file is what lets the program use it again next time.

  • Open a file with open("players.csv", "r"): r reads, a appends, and w writes but erases any existing file with the same name.
  • Have a goA classmate opens scores.csv with mode "w" so they can read yesterday's scores first. What will they find in the file?

    Nothing: mode w erased the existing file.

    w erases any existing file with the same name. Reading needs r, and adding to the end of an existing file needs a.

  • Call file.close() once all tasks are done: it frees system resources and protects the data.
  • Use file.read() for the whole contents, or for line in file: line by line; line.strip() removes each new line character.
  • A line is read as one string, so line.split(",") breaks it at the commas into a list.
  • Have a goA line arrives as "Kai,18\n". After line.strip() and then line.split(","), what list do you end up with?

    ['Kai', '18']

    strip() takes off the new line character, then split(",") breaks the string at the comma. Both items come out as strings.

  • Appending each split line to data builds a 2D list, and data[location][1] picks out an item.
  • Data read from a file is always held as strings, so cast it first, for example int(line.strip()).
  • Only strings can be written: convert each item first, for example str(number). Writing an integer or a list directly causes a TypeError.
  • Have a goYour classmate says: "file.write() is clever. It will turn my list [3, 5, 8] into text for me." Do you agree?

    No. Only strings can be written, and writing a list directly causes a TypeError.

    write() does not convert anything for you. Each item has to be turned into a string first, for example with str().

  • ",".join(str_numbers) makes one comma-separated row, the opposite of split(); for a 2D list, join each row and end it with "\n".

The big picture

A CSV (comma-separated values) file is a plain text file with one record per line and the items separated by commas. Python opens it like any text file, using the mode r, w or a. Reading it means stripping off the new line character, splitting each line at the commas and appending the lists to a 2D list, then casting values when you need other data types. Writing reverses this: convert items to strings, join each row with commas, end it with a new line character, write, and close the file.

Key points

1CSV stands for comma-separated values: plain text, one record per line, items separated by commas.
2The modes are r (read), w (write, erasing any existing file with the same name) and a (append).
3Reading: strip() removes the new line character, split(",") makes a list, append() builds a 2D list.
4Everything read from a file is a string, so cast it before using it as another data type.
5Writing: convert items to strings, join each row with commas, add a new line character, write, then close the file.

Worked example

Problem

players.csv already holds some records. A program has record = ["Sam", 15] and must add it as a new line at the end of the file, keeping the old records.

⚠ Watch out

Thinking a CSV file is a spreadsheet and that numbers in it come back as numbers. It is plain text: every line is read as a string, so values must be cast before arithmetic, and converted back to strings and joined before writing.

🧠

Memory hook

Reading goes strip, then split, then append, then cast. Writing runs it backwards: str, then join, then add the new line, then write.

✓

Check yourself

A program has just read the line "Ravi,30\n" from a CSV file. Which steps does it need before it can add 1 to Ravi's score?

Flashcards

(14)
What does CSV stand for?
Comma-separated values.
How is data laid out in a CSV file?
Each record is on a new line (a row), and the items in it are separated by commas, so the data is in rows and columns.
Why save a program's data to an external file?
So it can be used again when the program next runs. Data generated within a program is otherwise lost when the program is closed.
open("players.csv", "r"): what does the second argument do?
It sets the mode: r for reading, w for writing, a for appending.
What is special about mode w?
It erases any existing file with the same name.
Why call file.close()?
It closes the file once all tasks are done, freeing system resources and protecting the data.
What does line.strip() do to a line read from a file?
It removes leading and trailing white space, including the new line character at the end of the line.
What does line.split(",") give you?
A list of strings, made by breaking the line at the commas.
What do you get from data.append(line) for every split line?
A 2D list (a list of records), whose items you reach by index, for example data[location][1].
What type is data read from a file, and what must you do before arithmetic?
Always a string. Cast it first, for example int(line.strip()).
What happens if you write an integer or a list straight to a file?
A TypeError. Only string data can be written, so convert each item to a string first.
What does ",".join(str_numbers) do?
It joins a list of strings into one string with commas between the items, ready to write with file.write(data).
How are split() and join() related?
join() does the opposite of split().
When writing a 2D list, what goes on the end of each joined row?
A new line character, "\n", so that each record starts a new row in the file.

Tap any card to flip it, or use Study as deck to go through them one at a time. In the full lesson these run as a spaced-repetition deck — you rate each card Hard, Good or Easy and the tricky ones keep coming back until they stick.

Learning with Lightbulb is opening soon

You can use this lesson now. Join the waitlist and we'll let you know when the full Lightbulb experience is ready.

Keep me posted

More Edexcel GCSE Computer Science topics

See the full Edexcel Computer Science curriculum →

How this lesson was checked. This Edexcel GCSE Computer Science (specification 1CP2)lesson was published through Lightbulb Learning's human-designed editorial process — the educational standards, accuracy rules and publication checks it must pass were authored and approved by Philip Halpin. It passed subject-specific assessment, automated educational checks and technical publication verification before going live (publication checks completed 21 November 2026). Published pages are monitored, human spot-checking is ongoing across the lesson library, and anything found wrong is corrected or withdrawn. How our lessons are made and checked. Spotted a mistake? Email hello@lightbulblearning.co and we'll review it.