File handling

GCSE Computer Science (OCR) · OCR J277 · Algorithms and programming (Paper 2) › Programming fundamentals › Additional programming techniques

66 exam-style questions plus unlimited generated ones on this topic, at up to four difficulty levels, with full mark schemes. Notes and past-paper booklets are open to everyone. Practice needs a free account.

Or take a quick quiz: 10 questions on this subtopic in GCSE Computer Science (OCR), marked as you tap.

Revision notes

File handling lets a program store data permanently and read it back later. You need to open, read, write and close files, and create new ones, using the ERL commands. Expect short code questions and longer programs that read every line of a file.

Key facts

  • newFile("name.txt"): create a new file
  • f = open("name.txt"): open a file
  • f.readLine(): read the next line (always a string)
  • f.writeLine(data): write a line to the file
  • f.endOfFile(): True when there are no more lines
  • f.close(): close the file when finished
  • Read every line: while NOT f.endOfFile() … endwhile
  • Files keep data permanently; variables are lost when the program ends

Notes

Why use files

  • Variables are stored in RAM and are lost when the program closes.
  • A file is saved on secondary storage, so the data is kept after the program ends and can be read back the next time it runs (for example high scores or settings).
  • Files also let data be shared between programs.

File commands in ERL

diagram
  • newFile("scores.txt"): creates a new, empty file.
  • f = open("scores.txt"): opens the file, so the program can use it through the variable f.
  • line = f.readLine(): reads the next line from the file, as a string.
  • f.writeLine("Ava,42"): writes a line of data to the file.
  • f.endOfFile(): returns True when there are no more lines to read.
  • f.close(): closes the file. Always close a file when you have finished with it, so the data is saved and the file can be used by other programs.
  • open() the file first, close() it at the endProgramvariables in RAM(lost when theprogram closes)scores.txtAva,42Ben,37Cal,51f.writeLine()f.readLine()kept onsecondary storage
    Writing to and reading from a file

Reading every line

  • Use a while loop so it works for any number of lines, even an empty file:
    f = open("names.txt")
    while NOT f.endOfFile()
       name = f.readLine()
       print(name)
    endwhile
    f.close()
  • Each line is read as a string, so cast it (for example with int()) before doing arithmetic.

Writing to a new file

  • Create the file, open it, write each line, then close it:
    newFile("log.txt")
    f = open("log.txt")
    f.writeLine("Game started")
    f.close()

How to answer each type of question

Explain why data is stored in a file

2 marksGrade 4
  1. Say what happens to variables when the program closes.
  2. Say what the file allows: the data is kept and can be loaded next time.

Example. A game stores its high scores in a text file. Explain why the scores are stored in a file rather than only in variables. [2]

Show the model answerHide the model answer
Data stored in variables is lost when the program closes (1). A file keeps the scores permanently, so they can be read back the next time the game is played (1).

Write code to read a file

4 to 5 marksGrade 7
  1. Open the file.
  2. Loop until the end of the file, reading one line each time.
  3. Cast each line if it is a number and process it (total, count, compare).
  4. Close the file, then output the result.

Example. The file scores.txt holds one whole-number score on each line. Write a program that reads every score and outputs the total. [5]

Show the model answerHide the model answer
f = open("scores.txt")
total = 0
while NOT f.endOfFile()
   score = int(f.readLine())
   total = total + score
endwhile
f.close()
print(total)
Opens scores.txt (1); loops until the end of the file (1); reads a line each time and casts it to an integer (1); adds each score to a total set to 0 before the loop (1); closes the file and outputs the total (1).

Write code to write to a file

3 to 4 marksGrade 5
  1. Create the file with newFile() if it is new, then open it.
  2. Write each item with writeLine(), inside a loop if there are several.
  3. Close the file at the end.

Example. Write code that asks the user to enter 5 names and stores them in a new file called team.txt, one name per line. [4]

Show the model answerHide the model answer
newFile("team.txt")
f = open("team.txt")
for i = 1 to 5
   name = input("Enter a name")
   f.writeLine(name)
next i
f.close()
Creates and opens team.txt (1); loop that runs 5 times with a name input inside it (1); writes each name to the file with writeLine (1); closes the file after the loop (1).

Don’t lose marks

  • Forgetting to close the file.
  • Doing arithmetic on readLine() without casting it.
  • Using a for loop with a guessed number of lines instead of checking endOfFile().
  • Calling close() inside the loop, so the file is closed after the first line.
  • Opening the file inside the loop, which starts reading from the beginning again each time.

More tips

Memory tricks

  • File routine: Open, Read or Write, Close (O R/W C).
  • Anything read from a file is a string, just like input().
  • Unknown number of lines means a while NOT endOfFile() loop; never guess a fixed count.

Exam technique

  • Use the file name exactly as given in the question, in quotation marks.
  • Every file answer should include open and close: they are easy marks.
  • Put the output after the loop and after closing the file, unless the question asks for each line to be output.

What each grade needs

What you need to be able to do, from the first marks up to the top grade.

  1. Grade 4
    Explain why programs store data in filesData in variables is lost when the program ends; a file keeps it for next time.
  2. Grade 5
    Open, read and close a fileUse open(), readLine() and close() in the correct order.
  3. Grade 5
    Create a file and write to itUse newFile(), open() and writeLine(), then close the file.
  4. Grade 6
    Read every line until end of fileUse a while loop with NOT file.endOfFile().
  5. Grade 7
    Process data read from a fileCast each line to the right type, then total, count or search it.

Quick recall

Cover the answers and test yourself. The app has these as flashcards that come back just before you'd forget them.

Look at this program.
01 myFile = open("names.txt")
02 first = myFile.readLine()
03 myFile.close()
04 print(first)
State the name of the file used by the program.
names.txt
Look at this program.
01 f = open("colours.txt")
02 line1 = f.readLine()
03 f.close()
04 print(line1)
State the name of the file opened by the program.
colours.txt
State what the method readLine does when it is used on an open file.
It reads the next line of text from the file.
The program should write the text Went to the park to the file. Write the missing method name in line 02.
01 journal = open("journal.txt")
02 journal.________("Went to the park")
03 journal.close()
writeLine
Give one reason why a program might store its data in a file instead of keeping it only in variables.
The data is still there the next time the program is run.
The first line of a file holds the number 40. A program uses readLine to read that line. State the data type of the value that readLine returns.
String

Sample questions

Written for this site in the style of OCR exam questions. They are not taken from real past papers.

Question 1Easy3 marks
(a) A program writes data to a file. Put these three steps into the correct order: close the file, write the data, open the file.
[1]
(b) Give one reason why a program should close a file when it has finished using it.
[1]
(c) Give one reason why a program would store data in a file rather than only in variables.
[1]
Show the answer and mark scheme
(a)
  • open the file, write the data, close the file
(b)
  • so the file can be used by other programs / is not left locked
  • to make sure all the data is saved / written to the file
  • to free up the resources / memory used by the open file
(c)
  • data in variables is lost when the program ends, but data in a file is kept (so it can be used again next time the program runs)
Question 2Medium5 marks
The text file scores.txt contains one score on each line.
(a) Write an algorithm that reads every line of scores.txt and then outputs the number of lines in the file.
You must use either OCR Exam Reference Language or a high-level programming language that you have studied.
[4]
(b) Explain why a condition-controlled loop is used rather than a count-controlled loop.
[1]
Show the answer and mark scheme
(a) Answer:
f = open("scores.txt")
count = 0
while NOT f.endOfFile()
   line = f.readLine()
   count = count + 1
endwhile
f.close()
print(count)
  • opens scores.txt
  • loops until the end of the file is reached (e.g. while NOT f.endOfFile())
  • reads a line and adds 1 to a counter inside the loop (counter set to 0 before the loop)
  • closes the file and outputs the count after the loop
(b)
  • the number of lines in the file is not known in advance
Question 3Hard7 marks
The file results.txt contains test scores, one score on each line. The file contains at least one score.
(a) Write an algorithm that reads the scores from the file and outputs the mean score and the highest score.
You must use either OCR Exam Reference Language or a high-level programming language that you have studied.
[6]
(b) Explain why your algorithm would fail if the file was empty.
[1]
Show the answer and mark scheme
(a) Answer:
f = open("results.txt")
total = 0
count = 0
highest = -1
while NOT f.endOfFile()
   score = float(f.readLine())
   total = total + score
   count = count + 1
   if score > highest then
      highest = score
   endif
endwhile
f.close()
print("Mean: " + str(total / count))
print("Highest: " + str(highest))
  • opens the file (and closes it after reading)
  • loops until the end of the file
  • reads each score and converts it to a number
  • keeps a running total and a count of the scores
  • keeps track of the highest score (starting from the first score or a value lower than any score, and updating it when a larger score is read)
  • after the loop, calculates the mean as total ÷ count and outputs the mean and the highest score
(b)
  • count would be 0, so calculating the mean would divide by zero (error)

More in Additional programming techniques

Stuck? Get 1-to-1 help.

Chhetri Academy tutors GCSE and A level Maths and Science online, with a free 30-minute trial lesson.