Skip to main content
Engineering LibreTexts

7.2: Opening Files

[ "article:topic", "authorname:severancec", "python (language)", "license:ccbyncsa" ]
  • Page ID
    3112
  • 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

    >>> fhand = open('mbox.txt')
    >>> print(fhand)
    <_io.TextIOWrapper name='mbox.txt' mode='r' encoding='cp1252'>

     

    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.

    A File Handle

    A File Handle

    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>
    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.