File Handling (OCR GCSE Computer Science)
Revision Note
Written by: Robert Hampton
Reviewed by: James Woodhouse
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 |
|
|
End of file |
|
|
Create a new file |
|
|
Append a file |
|
|
Python example (reading data)
Employees | Text file |
---|---|
| Greg |
Python example (writing new data)
Employees |
|
| 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
title = input("Enter title")
1 mark for bothyear = input("Enter year")
file = open("books.txt")
1 mark
file.writeline(title)
1 mark for both
file.writeline(year)
file.close()
1 mark
Last updated:
You've read 0 of your 5 free revision notes this week
Sign up now. It’s free!
Did this page help you?