8.2. Opening files

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.py4e.com/code3/mbox.txt For learning purposes, we are using the shortened version of this file mbox-short.txt This file can be found and downloaded from www.py4e.com/code3/mbox-short.txt

Click on the button to show the first lines from this file.

If the open is successful, the operating system returns a file handle object. The file handle object 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.

A File Handle

If the file does not exist, open will fail with a traceback and you will not get a file handle object.

>>> fhand = open('stuff.txt')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FileNotFoundError: [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.

You have attempted of activities on this page