Subtopic Notes

K - File Handling

9-11. Data Types and Structures, Programming

File Handling

  • Text files consist of lines of text that are read or written consecutively as strings
  • The purpose of storing data in a file is to be used again by a program
  • Data in files are stored permanently, meaning they can be used later
  • It is good practice to explicitly open a file, stating the mode of operation, before reading from or writing to it.
  • File can be opened in three modes:
    • READ: for data to be read from the file
    • WRITE: for data to be written to the file. A new file will be created and any existing data in the file will be lost
    • APPEND: for data to be added to the file, after any existing data
  • A file should be opened in only one mode at a time

PYTHON

Python can be executed directly in the browser.

Editor — Python
Output
No output yet.

Opening a file

PSEUDOCODE

Pseudocode uses basic Cambridge-style keyword highlighting. Execution is not supported yet.

Editor — Pseudocode

The file identifier will be the name of the file with a data type of string.

Reading from a file

Data is read from the file, after opening in READ mode, using the following:

PSEUDOCODE

Pseudocode uses basic Cambridge-style keyword highlighting. Execution is not supported yet.

Editor — Pseudocode

When the command is executed, the data item is read and assigned to the variable. The data type is string.

Checking end of file

To test whether there are any more lines to be read from the file:

PSEUDOCODE

Pseudocode uses basic Cambridge-style keyword highlighting. Execution is not supported yet.

Editor — Pseudocode

This function returns TRUE if there are no more lines to read, or if an empty file has been opened in READ mode, and FALSE otherwise.

Writing to a file

Data is written into the file after opening using the following command:

PSEUDOCODE

Pseudocode uses basic Cambridge-style keyword highlighting. Execution is not supported yet.

Editor — Pseudocode

When the command is executed, the data is written into the file.

Closing a file

Files should be closed when they are no longer needed.

PSEUDOCODE

Pseudocode uses basic Cambridge-style keyword highlighting. Execution is not supported yet.

Editor — Pseudocode

Example: copying all lines from one file to another

This example uses the operations together, to copy all the lines from FileA.txt to FileB.txt, replacing any blank lines by a line of dashes.

PSEUDOCODE

Pseudocode uses basic Cambridge-style keyword highlighting. Execution is not supported yet.

Editor — Pseudocode