File Handling (Cambridge (CIE) A Level Computer Science): Revision Note

Exam code: 9618

Robert Hampton

Written by: Robert Hampton

Reviewed by: James Woodhouse

Updated on

File operations

What are file-processing operations?

  • File-processing involves interacting with external files stored on secondary storage (e.g. hard drives, SSDs)

  • In programming, files must be properly opened, read/written, and closed to ensure data is handled correctly

  • Different types of file access are also used

Common file operations

Operation

Description

Open

The file is opened in a specific mode:
read – to read data
write – to overwrite data
append – to add new data to the end

Read

Data (e.g. lines or records) is read from the file into memory

Write

Data is written to the file (overwriting or appending depending on mode)

Close

Ends access to the file and ensures all data is saved properly

Types of file access

Access type

Description

Serial access

Records are stored one after another, and accessed in the order they were added. Often used for logging

Sequential access

Records are read from the beginning to the end, in order. Common for batch processing and text files

Random access

Records can be accessed directly using a key or file position. Common in databases or indexed files

Programming file-operations

Pseudocode

Basic file operations

OPENFILE FOR // mode: READ, WRITE, APPEND, 
RANDOM READFILE , // read one line of text 
WRITEFILE , // write one line of text 
CLOSEFILE // always close the file

Serial access (e.g. logging events)

  • Data is written one after another (no specific order)

  • Often used with APPEND mode

Example: Writing logs serially

DECLARE LogEntry : STRING

LogEntry ← "12:00 System started"

OPENFILE "logfile.txt" FOR APPEND 
WRITEFILE "logfile.txt", LogEntry 
CLOSEFILE "logfile.txt"

Sequential access (e.g. reading through all records)

  • Records are read in order from start to end

  • Common for reports or summaries

Example: Reading student grades sequentially

DECLARE StudentLine : STRING

OPENFILE "students.txt" FOR READ

WHILE NOT EOF("students.txt") 
  READFILE "students.txt", StudentLine 
  OUTPUT StudentLine ENDWHILE

CLOSEFILE "students.txt"

Random access (e.g. accessing specific records by key)

  • Accesses records directly using a key (e.g. record number or unique ID)

  • Requires indexed files or fixed-length records

Example: Update a student’s grade by record position

TYPE Student DECLARE Name : STRING DECLARE Grade : INTEGER ENDTYPE

DECLARE ThisStudent : Student DECLARE RecordNumber : INTEGER

RecordNumber ← 5 // go directly to the 5th record

OPENFILE "students.dat" FOR RANDOM
SEEK "students.dat", RecordNumber GETRECORD "students.dat", ThisStudent
ThisStudent.Grade ← 90 // update grade
SEEK "students.dat", RecordNumber PUTRECORD "students.dat", ThisStudent
CLOSEFILE "students.dat"

Summary

Command

Purpose

Example

OPENFILE

Opens a file in a specified mode

OPENFILE "file.txt" FOR READ

READFILE

Reads one line from a text file

READFILE student FROM "file.txt"

WRITEFILE

Writes one line to a text file

WRITEFILE student TO "file.txt"

CLOSEFILE

Closes the file

CLOSEFILE "file.txt"

SEEK

Moves to a specific record (random access)

SEEK "file.txt", 5

EOF

Tests whether the end of the file has been reached

WHILE NOT EOF("file.txt")

GETRECORD

Reads the record at the file pointer

GETRECORD "file.dat", ThisStudent

PUTRECORD

Writes a record at the file pointer

PUTRECORD "file.dat", ThisStudent

Python

Basic file operations

file = open("filename.txt", "r" or "w" or "a")  # Open for read, write, or append
line = file.readline()                         # Read one line
file.write(data)                               # Write one line
file.close()                                   # Close the file

Serial access (e.g. logging events)

Example: Appending log entries to a file (serial write)

from datetime import datetime

message = "System started"
timestamp = datetime.now().strftime("%H:%M")

log = f"{timestamp} - {message}\n"

with open("logfile.txt", "a") as file:
    file.write(log)

Sequential access (e.g. reading through all records)

Example: Reading through each student line by line

with open("students.txt", "r") as file:
    for line in file:
        name, grade = line.strip().split(",")
        print(f"Name: {name}, Grade: {grade}")

Random access (e.g. accessing specific records by key)

Example: Update a student’s grade by index (record number)

record_number = 4  # 5th record (0-indexed)

with open("students.txt", "r") as file:
    records = file.readlines()

name, grade = records[record_number].strip().split(",")
records[record_number] = f"{name},90\n"  # Update grade to 90

with open("students.txt", "w") as file:
    file.writelines(records)

Summary

Operation

Python Example

Open

open("file.txt", "r")

Read

file.readline() / for line in file:

Write

file.write("text")

Close

file.close() or use with open(...)

Random access

lines = file.readlines() + list indexing

Java

Basic file operations

BufferedReader reader = new BufferedReader(new FileReader("filename.txt"));
String line = reader.readLine();
reader.close();

BufferedWriter writer = new BufferedWriter(new FileWriter("filename.txt", true)); // true = append
writer.write("Some text");
writer.newLine();
writer.close();

Serial access (e.g. logging events)

Example: Appending log entries to a file (serial write)

import java.io.*;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

public class SerialAccessExample {
    public static void main(String[] args) throws IOException {
        String message = "System started";
        String timestamp = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm"));
        String log = timestamp + " - " + message;

        BufferedWriter writer = new BufferedWriter(new FileWriter("logfile.txt", true));
        writer.write(log);
        writer.newLine();
        writer.close();
    }
}

Sequential access (e.g. reading through all records)

Example: Reading through each student line by line

import java.io.*;

public class SequentialAccessExample {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader("students.txt"));
        String line;

        while ((line = reader.readLine()) != null) {
            String[] parts = line.split(",");
            String name = parts[0];
            String grade = parts[1];
            System.out.println("Name: " + name + ", Grade: " + grade);
        }

        reader.close();
    }
}

Random access (e.g. accessing specific records by key)

Example: Update a student’s grade by index (record number)

import java.io.*;
import java.util.*;

public class RandomAccessExample {
    public static void main(String[] args) throws IOException {
        List<String> records = new ArrayList<>();
        int recordNumber = 4; // 5th line (0-indexed)

        BufferedReader reader = new BufferedReader(new FileReader("students.txt"));
        String line;
        while ((line = reader.readLine()) != null) {
            records.add(line);
        }
        reader.close();

        // Update the grade
        String[] parts = records.get(recordNumber).split(",");
        String updatedRecord = parts[0] + ",90";
        records.set(recordNumber, updatedRecord);

        // Overwrite the file
        BufferedWriter writer = new BufferedWriter(new FileWriter("students.txt"));
        for (String record : records) {
            writer.write(record);
            writer.newLine();
        }
        writer.close();
    }
}

Summary

Operation

Java Example

Open (read)

BufferedReader reader = new BufferedReader(...)

Read

reader.readLine() or while ((line = ...) != null)

Write

BufferedWriter writer = new BufferedWriter(...)

Append

new FileWriter("file.txt", true)

Close

reader.close() / writer.close()

Random access

RandomAccessFile (complex) or simulate with List

Unlock more, it's free!

Join the 100,000+ Students that ❤️ Save My Exams

the (exam) results speak for themselves:

Build on this topic

Robert Hampton

Author: Robert Hampton

Expertise: Curriculum Expert

Rob has over 16 years' experience teaching Computer Science and ICT at KS3 & GCSE levels. Rob has demonstrated strong leadership as Head of Department since 2012 and previously supported teacher development as a Specialist Leader of Education, empowering departments to excel in Computer Science. Beyond his tech expertise, Robert embraces the virtual world as an avid gamer, conquering digital battlefields when he's not coding.

James Woodhouse

Reviewer: James Woodhouse

Expertise: Portfolio Lead

James graduated from the University of Sunderland with a degree in ICT and Computing education. He has over 14 years of experience both teaching and leading in Computer Science, specialising in teaching GCSE and A-level. James has held various leadership roles, including Head of Computer Science and coordinator positions for Key Stage 3 and Key Stage 4. James has a keen interest in networking security and technologies aimed at preventing security breaches.