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.
CSV files
Ava,14
Ben,19
It is plain text, so many programs can read it.
Reading a file
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
"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()
A line in a file is Ava,14,Leeds. What does line.split(",") give?
- split(",") cuts the string at every comma.
- Each piece becomes a list item.
Answer: ['Ava', '14', 'Leeds']
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.
Try two quick questions
See if it has sunk in. Answers are marked straight away.
2 more questions
Try each one, then tap to check.
Which mode opens a file only to read it?
- "w"
- "a"
- "r"
- "x"
Show the answer
Answer: "r"
"r" means read.
What happens if you open a file that does not exist with "w"?
- An error occurs
- Nothing is written
- A new empty file is created
- 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.
- Pearson Edexcel GCSE Computer Science (1CP2) specification, topic 6.4.2
- Pearson Edexcel International GCSE Computer Science (4CP0) specification, topic 2.4.3
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? →