3. Open file

Input and output commands work very well for allowing a programmer to interact with a program that they are writing. The problem, though, is that the results of these interactions are temporary. As soon as the program ends, it will forget all of the data put in and all of the data it has provided.

A more permanent way of storing data is needed. This is the purpose of a file. A file stores information in secondary memory such as hard disk or USB thumb drive, and programs can retrieve and edit the contents of a file as needed.

There are a number of specialised commands used in programs for handling files. The first of these is the open command.

A 'file open' command in programming means 'prepare the file, ready for use'.

In pseudocode, the command is OPEN:

Myfile ??? OPEN ('filename', 'mode')

The OPEN command has two arguments. The first is the name of the file, and the other is the 'mode' in which the file is to be opened.

File names and file handles

In the example above, 'Myfile' is a file handle - a temporary label used by the program itself to identify that file.

File handles are useful because file names can get very long and cumbersome. Rather than having to type out a long file name like "Personal account sheets from 2005-2015 - Andy and Bob.xls" every time, you can assign a short file handle like 'Myfile' to a variable and use that throughout the program.

File modes

The second argument in the OPEN command is the 'mode'. You don't always want to give programs permission to do whatever they want with files. The mode tells the program what it is allowed to do with a file. These are the modes:

File open modes

Mode

Description

'r'

Read Only. Allows data in the file to be read. You can only use Read Only mode on files that already exist - it can't create new files.

'w'

Write mode. If the file exists, all of the data currently inside of it is discarded and new data is written over the top of it. If the file does not exist, Write mode will create an empty file.

'a'

Append. Much like write, this allows data to be written into an existing file or into a new file. But where write mode writes over the top of whatever was there, append mode adds its changes to the end of the file. Existing data is kept intact.

'r+' or 'w+'

Allow both read from and write to the file. W+ mode will also blank existing files, while R+ does not.

'a+'

Open or create a file for reading and allow data to be written at the end of the file.

Challenge see if you can find out one extra fact on this topic that we haven't
already told you