- Home
- Lessons
- GCSE & IGCSE Computer Science
- Reading and writing CSV text files
Reading and writing CSV text files
🎬 The doodle video for this lesson is coming soon. Subscribe on YouTube to see it first.
Variables are lost when a program ends. Text files let programs save data and load it again next time.
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.
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()
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()
"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.
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.