teach-ict.com logo

THE education site for computer science and ICT

2. Open File

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

In Python, the command is:

                         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 handles

The open command returns 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 something 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 that Python 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

Click on this link: Python command to open a file