File Handling (OCR GCSE Computer Science): Revision Notes
📚 Revision Notes
File Handling
File handling allows programmes to store, retrieve, and update data on disc, making it essential for tasks like saving user information or reading configuration files. There are four key file operations: open, read, write, and close.
Opening a File
- Before reading from or writing to a file, it must be opened.
- This is done using the
opencommand in most programming languages. - Files can be opened in different modes, such as reading mode (
read), writing mode (write), or append mode (adding data to an existing file).
Example (Pseudocode)
myFile = open("computing.txt")
In the example, the file "computing.txt" is opened for processing.
Reading from a File
- Reading a file means extracting data from it.
- Typically, files are read line by line or in chunks.
- A
whileloop can be used to read until the end of the file is reached.
Example (Pseudocode)
myFile = openRead("computing.txt")
while NOT myFile.endOfFile()
print(myFile.readLine())
endwhile
myFile.close()
This pseudocode reads each line of "computing.txt" and prints it until the end of the file is reached, then closes the file.
Writing to a File
- Writing to a file involves creating or opening a file and adding data to it.
- If the file already exists, its contents may be overwritten unless it is opened in append mode.
- Always ensure to close the file after writing to it to save changes.
Example (Pseudocode)
myFile = openWrite("sample.txt")
myFile.writeLine("Hello World")
myFile.close()
This pseudocode creates or opens the file "sample.txt" and writes the text "Hello World" to it, then closes the file.
Closing a File
- Once a programme has finished reading from or writing to a file, the file must be closed to free up system resources and ensure that all data is properly saved.
Practical Use
- Here is how to practice file-handling techniques using a high-level programming language like Python.
- For example, in Python:
open("file.txt", "r")opens a file for reading.open("file.txt", "w")opens a file for writing.file.close()closes the file after processing.
infoNote
Key Points to Remember:
- Open: Opens a file for reading or writing.
- Read: Retrieves data from a file, usually line by line or in chunks.
- Write: Writes or appends data to a file.
- Close: Closes the file after reading or writing to ensure changes are saved.