Reading and writing CSV text files

Variables are lost when a program ends. Text files let programs save data and load it again next time.

Practise this lesson free (6 questions)

More tools

CSV files

A comma separated value (CSV) file stores one record per line, with fields separated by commas:
Ava,14
Ben,19
It is plain text, so many programs can read it.

Reading a file

open(filename, "r") opens a file for reading.
A for loop reads one line at a time. strip() removes the newline at the end, and split(",") breaks the line into a list of fields.
Always close() the file when you are finished.
file = open("scores.txt", "r")
for line in file:
    fields = line.strip().split(",")
    print(fields[0], "scored", fields[1])
file.close()

Writing a file

"w" mode creates the file, or overwrites it if it already exists.
"a" mode appends: it adds to the end and keeps what is there.
write() does not add a new line by itself, so add \n.
file = open("scores.txt", "a")
file.write("Ravi,17\n")
file.close()
Worked example

A line in a file is Ava,14,Leeds. What does line.split(",") give?

  1. split(",") cuts the string at every comma.
  2. Each piece becomes a list item.

Answer: ['Ava', '14', 'Leeds']

Key idea

CSV files hold one record per line with comma-separated fields. Open with "r" to read, "w" to overwrite, "a" to append. Use strip() and split(",") to get the fields, then close() the file.

Quick check

Try two quick questions

See if it has sunk in. Answers are marked straight away.

Extra practice

2 more questions

Try each one, then tap to check.

  1. Which mode opens a file only to read it?

    1. "w"
    2. "a"
    3. "r"
    4. "x"
    Show the answer

    Answer: "r"

    "r" means read.

  2. What happens if you open a file that does not exist with "w"?

    1. An error occurs
    2. Nothing is written
    3. A new empty file is created
    4. The file is read
    Show the answer

    Answer: A new empty file is created

    "w" creates the file if needed.

Check you have got it

Answer 6 quick questions with instant marking. If you get one wrong, GCSE-ready shows you why and gives you another go. It is free, and you do not need an account.

Video for this lesson coming soon. Subscribe on YouTube

Sources and references

Facts checked against the sources below, 17 October 2026. Last updated 2 October 2026. Spotted a mistake? Tell us and we will fix it.

What do exam command words like explain and evaluate mean? →

Related lessons