ComputerScienceUK.
com CSUK:Teacher
File Handling
Quick Reference
Construct Setup Example
Create a New File newFile() newFile("myFile.txt")
This simply creates a new text file called "myFile". The file still needs to be
opened using the open() statement (see below).
Open open(…) myFileHandler = open("myFile.txt")
When opening a file, it must be assigned to a file handler.
Close .close() myFileHandler.close()
Read Line .readLine() myFileHandler.readLine() returns the next line in the file
Write Line .writeLine(…) myFileHandler.writeLine("Some Text")
The line will be written to the end of the file.
End of File .endOfFile() while NOT myFileHandler.endOfFile()
print(myFileHandler.readLine())
endwhile
File Handling
File handling involves the reading from and writing to a file, that is external to the program. When programs store data
in variables and arrays, the data itself is actually store in the RAM, which is volatile and as such, when the program
closes, the data is lost.
It is therefore often required that our programs write data to an external file, so that when the program is closed and
reopened again at a later date, the saved data can be retrieved.
When writing algorithms, we can demonstrate the logic for this in the following ways.
Creating a New File
We can demonstrate the creation of a new external file by writing newFile(), with the name of the file and its file
type, written within quotes, inside the brackets.
For example, newFile(“myNewFile.txt”) would demonstrate the creation of a text file, with the name
myNewFile.
Opening a File
In order for programs to begin working with an external file, they will first need to open the file. This can be
demonstrated in our algorithms by writing open(), with the name of the file and its file type, written within quotes,
inside the brackets.
But what is important here is that we assign a file handler to this process!
For example, myFileHandler = open(“myNewFile.txt”) would demonstrate the opening of the text file, with
the name myNewFile, inside the program, assigning it to a file handler called ‘myFileHandler’.
You can think of a file handler as a data structure, which keeps track of how the file is being used by the program. For
example, as the file is being read by the program, the file handler will keep track of where the program has read up to,
using a cursor.
Computer Science UK Membership Site Licence: Do not share outside of your centre 1
ComputerScienceUK.com CSUK:Teacher
Reading a Line from a File
Once we have demonstrated the opening of a file, we can begin to show how our program will read the file using a
.readLine() method.
myNewFile.txt
For example, imagine we have a text file, which contains three lines of text, and have This is line one
opened the file in our program and assigned it to a file handler: myFileHandler =
open(“myNewFile.txt”) This is line two
If we write myFileHandler.readLine(), this will demonstrate the reading of the This is the last line!
next line of the file. So, if used immediately after opening the file, it will be the first line
of the file that is read. If repeated, the next line will be read, and so on.
Remember that there will be an invisible cursor which will track where the file has been read up to. .readLine()
will read the next line that follows the current position of the cursor, and will move the cursor on to the end of that line
after it is read by the program.
File Example Algorithm Output
This is line one
myFileHandler = open(“myNewFile.txt”) This is line two
print(myFileHandler.readLine()) This is the last line!
print(myFileHandler.readLine())
print(myFileHandler.readLine())
Writing a Line to a File
To demonstrate the writing of data to a file, we can use a .writeLine() method.
For example, imagine we have some data that we want to write to a file. Once we have opened the file in our program
and assigned it to a file handler myFileHandler = open(“myNewFile.txt”) we can write
myFileHandler.writeLine() and place either a hardcoded string or a variable in the brackets, to have the data
written to the open file.
Example Algorithm File Contents
(after algorithm is executed)
myNewFile.txt
name = “Anna”
favouriteColour = “green” Anna
myFileHandler = open(“myNewFile.txt”) green
myFileHandler.writeLine(name)
myFileHandler.writeLine(favouriteColour) The End
myFileHandler.writeLine(“The End”)
Computer Science UK Membership Site Licence: Do not share outside of your centre 2
ComputerScienceUK.com CSUK:Teacher
Checking if the Cursor is at the End of a File
Quite often, when we work with external files, we will not know how many lines of data the file will contain.
Thankfully most languages have a built-in method which can see if the file’s cursor is at the end of the file or not. This
means that we can create loops to read line after line of an external file and stop as soon as the cursor reaches the end
of the file.
The following algorithm can show the logic of such a scenario:
while NOT myFileHandler.endOfFile()
print(myFileHandler.readLine())
endwhile
Closing a File
Once we have finished working with an external file, it is sensible to close the connection to the file. This can be
achieved by appending a .close() method to the end of the file handler. The final line of the following algorithm
demonstrates this:
myFileHandler = open(“myNewFile.txt”)
print(myFileHandler.readLine())
myFileHandler.close()
Algorithm Writing Guidance – File Handling
Consider the algorithm question:
Write an algorithm, which will ask the user to enter their favourite film and write the inputted
information
Computer Science UKto a text Site
Membership file.
Licence: Do not share outside of your centre 3
ComputerScienceUK.com CSUK:Teacher
As before, let’s begin by breaking this question down into its component parts. This problem has arguably 5 main
parts to it:
1) Ask the user to input data and store in a variable
2) Create a text file
3) Open the text file and assign a file handler
4) Write the variable contents to the file
5) Close the file
For point one, we will need a simply input() statement and assign to it a variable to store the input:
film = input(“Enter your favourite film: ”)
For point 2, we need to demonstrate the creating of a text file:
film = input(“Enter your favourite film: ”)
newFile(“favFilm.txt”)
For point 3, we will need to open the file and assign it to a file handler:
film = input(“Enter your favourite film: ”)
newFile(“favFilm.txt”)
myFileHandler = open(“favFilm.txt”)
We are now in a position to carry out point 4 which is to write the contents of the variable ‘film’ to the file, which can
be demonstrated like this:
film = input(“Enter your favourite film: ”)
newFile(“favFilm.txt”)
myFileHandler = open(“favFilm.txt”)
myFileHandler.writeLine(film)
Finally, we can complete the final step (point 5) and close the connection to the file:
film = input(“Enter your favourite film: ”)
newFile(“favFilm.txt”)
myFileHandler = open(“favFilm.txt”)
myFileHandler.writeLine(film)
Computer Science UK Membership SitemyFileHandler.close()
Licence: Do not share outside of your centre 4
ComputerScienceUK.com CSUK:Teacher
Practice Questions – File Handling
Worked Example
Write an algorithm that will open a text file called “top5Films.txt”, read and output the contents of the text file, in its
entirety.
The file is opened and assigned to a file handler
A while loop is set to iterate while the
file handler is not at the end of the file. myFileHandler = open(“top5Films.txt”)
Within the loop, each line of the
while NOT myFileHandler.endOfFile() file is outputted, one line at a
time.
This identifies the end of print(myFileHandler.readLine())
the loop structure.
endwhile
Computer Science UK Membership Site Licence: Do not share outside of your centre 5
ComputerScienceUK.com CSUK:Teacher
The connection to the file is
closed.
Question 1 Algorithm
Write an algorithm that will create a text file with open('myFile.txt', 'w') as file:
called ‘myFile.txt’, open the file, then write the file.write('This is the first line')
string ‘This is the first line’ to the text file,
before closing it.
Question 2 Algorithm
Write an algorithm that will open a text file with open('HighScore.txt', 'r') as file:
called ‘HighScore.txt’ (which contains a list of top_score = file.readline()
high scores in descending order) and output the print(top_score)
top score (first line).
Question 3 Algorithm
Write an algorithm that will open a text file with open('examFeedback.txt', 'r+') as file:
called “examFeedback.txt”, read and output content = file.read()
the entire contents of the text file, then ask the print(content)
user to enter a comment and write this to the user_comment = input("Enter your comment: ")
end of the file, before closing it. file.write(user_comment)
Computer Science UK Membership Site Licence: Do not share outside of your centre 6