teach-ict.com logo

THE education site for computer science and ICT

3. Opening files

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) for (Purpose)

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.

image

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 purpose, the reason you are opening the file. This is also called the 'file 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
'reading' 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.
'writing data' 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.
'appending data' 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.
                         Myfile  OPEN productFile for reading

You can combine modes if necessary, e.g. opening a file for both reading and writing. Once you are done, you can close the file with the CLOSE command.

                        CLOSE Myfile