LambdaLabTM
Computer Science · Class 12 · Text Files
Text filesopen()⏱️ 12 min read

Opening a Text File

The last chapter said what a file is and how to write down where it lives. It never opened one. That takes a single function — open() — and what it hands back is not the file and not the writing inside it, which is the part worth slowing down for.

1One function does it: open()

A program cannot reach into a file directly. It has to ask the operating system for permission first, and open() is that request. You tell it two things: which file, and what you intend to do with it.

f = open('notes.txt', 'r')
the filename

A string. The name of the file, or a path to it.

the mode

A string too. What you plan to do: read, write, or add on.

Both are ordinary strings, so both need quotes. And the mode is what the next lesson is entirely about — here we only ever use 'r', which means read this file and change nothing.

2What open() hands back

open() gives you a file object — also called a file handle. Print it and you can see it is not the text of the file at all:

the_handle.py
f = open('notes.txt', 'r')

print(f)
print(f.name)
print(f.mode)
print(f.closed)

f.close()
print(f.closed)
Output
<_io.TextIOWrapper name='notes.txt' mode='r' encoding='UTF-8'>
notes.txt
r
False
True
f is a handle, not the file
Think of a library. The book stays on the shelf; what the librarian hands you is a ticket. The ticket is not the book, and it is not the story inside it — it is your right to go and read that book, and a note of where you had got to. f is the ticket. The file is still on the disk.

The handle knows three useful things about itself, and they are all printed above:

f.name
'notes.txt'

The filename you asked for, exactly as you typed it.

f.mode
'r'

The mode it was opened in. It cannot be changed afterwards.

f.closed
False

Is this handle finished with? False while the file is open.

Why encoding='UTF-8' is in there
A text file holds character codes, and the encoding is the rulebook that says which number stands for which character. Python picks your computer's default, so a Windows machine may print cp1252 where this one printed UTF-8. Nothing in this chapter depends on it.

3The mode is optional

Leave the mode out and Python uses 'r'. These two lines do exactly the same thing:

same_thing.py
f = open('notes.txt', 'r')
f.close()

f = open('notes.txt')
print(f.mode)
f.close()
Output
r
Tip
Write the mode anyway. open('notes.txt') works, but open('notes.txt', 'r') says out loud that this program only reads — and in an exam it shows the examiner you knew there was a choice to make.

4Every file program is the same three steps

Open it, use it, close it. That order never changes, in any language, for any file.

Step 1 · Open
f = open('notes.txt', 'r')

Ask for the file and get a handle back.

Step 2 · Use
data = f.read()

Read from it or write to it, through the handle.

Step 3 · Close
f.close()

Hand the ticket back. The file is free again.

Here is the whole round trip in five lines, with one new method in the middle of it.

data = f.read()

read() hands back everything in the file, as one string. That is all you need from it for the next few lessons, and it is the only reading method used until read(), readline() and readlines(), which takes it apart properly.

round_trip.py
📄 notes.txt
Note
Hover the 📄 notes.txt pill above the code to see what is in the file. It is a real file in the browser's own little disk, so every program on this page runs for you exactly as it ran here.

5When the file is not there

Mode 'r' never creates a file. If nothing of that name is in the folder, open() stops the program on the spot:

missing.py
f = open('marks.txt')
print(f.read())
f.close()
Output
Traceback (most recent call last):
  File "missing.py", line 1, in <module>
    f = open('marks.txt')
        ^^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'marks.txt'

You met FileNotFoundError in the Exception Handling chapter, and this is where it earns its keep. A program that reads a file the user chose should never fall over with a traceback:

guarded.py
try:
    f = open('marks.txt', 'r')
    print(f.read())
    f.close()
except FileNotFoundError:
    print('That file is not in this folder.')
Output
That file is not in this folder.
Two spellings, one mistake
FileNotFoundError is the class name and the traceback is the message. Catching except FileNotFound: is a NameError — there is no such class. And catching except: on its own catches the typing mistakes too, which the Catching the Right One lesson explains at length.

6Where Python goes looking

open('notes.txt') is a relative path, so Python starts in the folder the program is running from. That is why the same program finds the file on your machine and not on your friend's: the file has to sit beside the program, or you have to say more about where it is.

three_addresses.py
# in the same folder as the program
f = open('notes.txt', 'r')
f.close()

# in a folder called data, next to the program
f = open('data/notes.txt', 'r')
f.close()

# the full address, from the drive down
f = open('C:/school/notes.txt', 'r')
f.close()
Tip
Forward slashes, even on Windows. 'C:\school\notes.txt' is the trap the Relative & Absolute Paths lesson takes apart: \n inside a string is a newline, not a folder.

7Recap

open(filename, mode)

Two strings: which file, and what you plan to do with it. The mode may be left out, and then it is 'r'.

It hands back a file object

The handle. Not the file, not its contents — your connection to it, held in a variable, usually called f.

f.name, f.mode, f.closed

What the handle knows about itself. f.closed is False while the file is open and True after close().

Open, use, close

The three steps of every file program, in that order, without exception.

'r' never creates a file

No such file, and open() raises FileNotFoundError before your program has read a thing.

The filename is a path

A bare name means 'in the folder this program is running from'. Anything else needs the path written out.

✍️ Now write these yourself
  1. 1

    Make a file called notes.txt in the same folder as your program, open it, and print f.name and f.mode.

    Hint · Three lines and a close(). Nothing is read yet.

  2. 2

    Print f.closed twice — once before f.close() and once after.

    Hint · False, then True. The handle outlives the connection.

  3. 3

    Open a file that does not exist, and catch the error so your program prints a sentence instead of a traceback.

    Hint · try / except FileNotFoundError, exactly as above.

  4. 4

    Move notes.txt into a subfolder called data and make the program find it again.

    Hint · Only the string inside open() changes.

Quick Check

What does open('notes.txt', 'r') give back?

Quick Check

open('notes.txt') and open('notes.txt', 'r') are...

Quick Check

The file marks.txt does not exist. What does open('marks.txt', 'r') do?

Quick Check

After f.close(), what is f?