8.3 File handling

← Topic 8.2 ArraysComputer Science contentsTopic 9.1 Databases →
Chapter 8 · Programming

8.3 File handling

Programs often need data to remain available after the program has finished or the computer has been switched off. This topic explains why data is stored in files and how programs can write data to a file and later read it back.

Permanent storageFilenamesWriteReadClose files

8.3.1 Purpose of storing data in a file

Data held in RAM is lost when the computer is switched off. If a program will need the data again, the data can instead be saved in a file, where it is stored permanently.

Where data is heldWhat happens
RAMData is temporary and is lost when the computer is switched off.
FileData is stored permanently so that it can be used again later.

Once data has been saved in a file, it can be:

Key idea: a file is used when data must survive beyond the current run of a program. The textbook describes file storage as one of the most commonly used features of programming.
Check why programs use files.

8.3.2 Using files

Every file is identified by its filename. For IGCSE Computer Science, you need to understand how a program can write a line of text or a single item of data to a file and then read it back.

The basic file-handling sequence

StagePurpose
1. Identify the fileUse a filename so the program knows which file to use.
2. Open the fileOpen it for the required operation, such as reading or writing.
3. Read or writeTransfer data from the file into the program, or from the program into the file.
4. Close the fileClose the file after the operation has finished.

Pseudocode example from the textbook

The source example stores the filename in MyFile, writes a line of text, closes the file, reopens it for reading, reads the line and displays it.

DECLARE TextLine : STRING   // variables are declared as normal
DECLARE MyFile : STRING
MyFile ← "MyText.txt"

// writing the line of text to the file
OPEN MyFile FOR WRITE       // opens file for writing
  OUTPUT "Please enter a line of text"
  INPUT TextLine
  WRITEFILE, TextLine       // writes a line of text to the file
CLOSEFILE(MyFile)           // closes the file

// reading the line of text from the file
OUTPUT "The file contains this line of text:"
OPEN MyFile FOR READ        // opens file for reading
  READFILE, TextLine        // reads a line of text from the file
  OUTPUT TextLine
CLOSEFILE(MyFile)           // closes the file
Source notation: the textbook prints the pseudocode operations as WRITEFILE, TextLine and READFILE, TextLine after the file has been opened. These notes retain that printed notation rather than silently changing it.

What each pseudocode command is doing

CommandMeaning in this example
OPEN MyFile FOR WRITEOpens the named file so that data can be written to it.
WRITEFILE, TextLineWrites the value stored in TextLine to the open file.
CLOSEFILE(MyFile)Closes the file after writing or reading has finished.
OPEN MyFile FOR READOpens the named file so that data can be read from it.
READFILE, TextLineReads a line from the open file and stores it in TextLine.
Check the file-handling sequence and pseudocode.

Python example

# writing to and reading a line of text from a file
MyFile = open ("MyText.txt","w")
TextLine = input("Please enter a line of text ")
MyFile.write(TextLine)
Myfile.close()

print("The file contains this line of text")
MyFile = open ("MyText.txt","r")
TextLine = MyFile.read()
print(TextLine)
Myfile.close()

In the example, "w" is used when the file is opened for writing and "r" when it is opened for reading. The line entered by the user is written to the file, read back and then displayed.

Printed-code note: the textbook uses MyFile when opening the file but Myfile on the two close lines. The example above preserves the source spelling. When students write runnable Python, identifier spelling and capitalisation need to be used consistently.

Visual Basic example

'writing to and reading from a text file
Imports System.IO
Module Module1
  Sub Main()
    Dim textLn As String
    Dim objMyFileWrite As StreamWriter
    Dim objMyFileRead As StreamReader

    objMyFileWrite = New StreamWriter("textFile.txt")
    Console.Write("Please enter a line of text ")
    textLn = Console.ReadLine()
    objMyFileWrite.WriteLine(textLn)
    objMyFileWrite.Close()

    Console.WriteLine("The line of text is ")
    objMyFileRead = New StreamReader("textFile.txt")
    textLn = objMyFileRead.ReadLine
    Console.WriteLine(textLn)
    objMyFileRead.Close()
    Console.ReadLine()
  End Sub
End Module

The Visual Basic example imports System.IO, uses a StreamWriter to write the text, closes it, then uses a StreamReader to read the stored line back.

Java example

// writing to and reading from a text file
// try and catch implement exception handling; the textbook notes that
// exception handling is beyond IGCSE level
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

class TextFile {
  public static void main(String[] args) {
    Scanner myObj = new Scanner(System.in);
    String textLn;
    try {
      FileWriter myFileWriter = new FileWriter("textFile.txt", false);
      PrintWriter myPrintWriter = new PrintWriter(myFileWriter);
      System.out.println("Please enter a line of text ");
      textLn = myObj.next();
      myPrintWriter.printf("%s" + "%n", textLn);
      myPrintWriter.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
    try {
      FileReader myFileReader = new FileReader("textFile.txt");
      BufferedReader myBufferReader = new BufferedReader(myFileReader);
      textLn = myBufferReader.readLine();
      System.out.println(textLn);
      myFileReader.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

The Java example imports the file-handling classes it needs, writes the text using FileWriter and PrintWriter, then reads it back using FileReader and BufferedReader. The textbook explicitly states that the try/catch exception-handling concept is beyond IGCSE level.

Check the language examples and file operations.

Copying data from one text file to another

The chapter activity asks you to apply the same ideas to copy a line of text from one text file to another. The logic is:

OPEN source file FOR READ
READ the line into a variable
CLOSE the source file
OPEN destination file FOR WRITE
WRITE the stored line to the destination file
CLOSE the destination file

This is not a new kind of file operation: it combines the same read and write steps already used above.

Topic 8.3 revision checklist

Explain why data in RAM is temporary.
Explain why a file is used when data is needed again later.
State that a file is identified by its filename.
Explain that stored file data can be used later by the same program, another program or another computer.
Open a file for writing and write a line or item of data.
Close a file after writing.
Open a file for reading and read stored data into a variable.
Close a file after reading.
Follow the textbook pseudocode file-handling sequence.
Recognise the equivalent Python, Visual Basic and Java examples.
Apply read/write operations to copy a line of text from one file to another.
Ready for a mixed Topic 8.3 check?
← Topic 8.2 ArraysComputer Science contentsTopic 9.1 Databases →