File Handling (Cambridge (CIE) O Level Computer Science): Revision Note
Exam code: 2210
File Handling
What is file handling?
File handling is the use of programming techniques to work with information stored in text files
Examples of file handing techniques are:
opening text files
reading text files
writing text files
closing text files
Concept | OCR exam reference | Python |
---|---|---|
Open |
|
|
Close |
|
|
Read line |
|
|
Write line |
|
|
Append a file |
|
|
Pseudocode example (reading data)
Employees | Text file |
---|---|
| Greg |
Python example (reading data)
Employees | Text file |
---|---|
| Greg |
Pseudocode example (writing new data)
Employees | Text file |
---|---|
| Greg Polly |
Python example (writing new data)
Employees | Text file |
---|---|
| Greg |
Examiner Tips and Tricks
When opening files it is really important to make sure you use the correct letter in the open command
"r" is for reading from a file only
"w" is for writing to a new file, if the file does not exist it will be created. If a file with the same name exists the contents will be overwritten
"a" is for writing to the end of an existing file only
Always make a backup of text files you are working with, one mistake and you can lose the contents!
Worked Example
Use pseudocode to write an algorithm that does the following :
Inputs the title and year of a book from the user.
Permanently stores the book title and year to the existing text file books.txt [4]
How to answer this question
Write two input statements (title and year of book)
Open the file
Write inputs to file
Close the file
Example answer
title = input("Enter title")
year = input("Enter year")
file = open("books.txt")
file.writeline(title)
file.writeline(year)
file.close()
Guidance
| 1 mark |
| |
| 1 mark |
| 1 mark |
| |
| 1 mark |
You've read 0 of your 5 free revision notes this week
Unlock more, it's free!
Did this page help you?