File Handling (Cambridge (CIE) O Level Computer Science)
Revision Note
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 |
|
|
Python example (reading data)
Employees | Text file |
| Greg |
Python example (writing new data)
Employees |
|
| Greg |
Exam Tip
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 markfile.writeline(title)
1 mark for bothfile.writeline(year)
file.close()
1 mark
You've read 0 of your 10 free revision notes
Unlock more, it's free!
Did this page help you?