Records and files
Reading and writing text files, splitting a line into the fields of a record, totalling, filtering and updating records, reading until a rogue value, and completing and refining a program.
Files and records
A text file stores lines of text. A record is one line that holds several fields, often separated by commas: Aisha,15,Leeds holds a name, an age and a town.
# Reading a file in Python
file = open("members.txt", "r")
for line in file:
line = line.strip()
print(line)
file.close()
# Writing to a file
file = open("scores.txt", "w")
file.write("Aisha,42\n")
file.close()
OCR style uses openRead, readLine(), endOfFile() and close(); AQA papers describe the file in words. In the questions here the lines have already been read into a list of strings, one string per line, so you can concentrate on what to do with them.
The rest of this lesson and its 9 practice questions are in Plus.
Screen 1 of 5, free to read.
- 9 exam-style questions, marked as you go, each with a worked solution
- Anything you get wrong is saved to your flashcards