11 File Handling
11 File Handling
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.
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.
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
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.
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.
Computer Science UK Membership Site Licence: Do not share outside of your centre 2
ComputerScienceUK.com CSUK:Teacher
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()
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:
For point 3, we will need to open the file and assign it to a file handler:
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:
Finally, we can complete the final step (point 5) and close the connection to the file:
endwhile
Computer Science UK Membership Site Licence: Do not share outside of your centre 5
ComputerScienceUK.com CSUK:Teacher
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