You are here

Opening files

23 February, 2015 - 16:21

When we want to read or write a file (say on your hard drive), we first must open the file. Opening the file communicates with your operating system which knows where the data for each file is stored. When you open a file, you are asking the operating system to find the file by name and make sure the file exists. In this example, we open the file mbox.txt which should be stored in the same folder that you are in when you start Python. You can download this file from www.py4inf.com/code/mbox.txt

>>> fhand = open('mbox.txt')>>> print fhand<open file 'mbox.txt', mode 'r' at 0x1005088b0>

If the open is successful, the operating system returns us a file handle. The file handle is not the actual data contained in the file, but instead it is a “handle” that we can use to read the data. You are given a handle if the requested file exists and you have the proper permissions to read the file.

media/image11.png

If the file does not exist, open will fail with a traceback and you will not get a handle to access the contents of the file:

>>> fhand = open('stuff.txt')Traceback (most recent call last):  File "<stdin>", line 1, in <module>IOError: [Errno 2] No such file or directory: 'stuff.txt'

Later we will use try and except to deal more gracefully with the situation where we attempt to open a file that does not exist.