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')A string. The name of the file, or a path to it.
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:
f = open('notes.txt', 'r')
print(f)
print(f.name)
print(f.mode)
print(f.closed)
f.close()
print(f.closed)<_io.TextIOWrapper name='notes.txt' mode='r' encoding='UTF-8'> notes.txt r False True
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.nameThe filename you asked for, exactly as you typed it.
f.modeThe mode it was opened in. It cannot be changed afterwards.
f.closedIs this handle finished with? False while the file is open.
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:
f = open('notes.txt', 'r')
f.close()
f = open('notes.txt')
print(f.mode)
f.close()r
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.
f = open('notes.txt', 'r')Ask for the file and get a handle back.
data = f.read()Read from it or write to it, through the handle.
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.
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:
f = open('marks.txt')
print(f.read())
f.close()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:
try:
f = open('marks.txt', 'r')
print(f.read())
f.close()
except FileNotFoundError:
print('That file is not in this folder.')That file is not in this folder.
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.
# 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()'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
Two strings: which file, and what you plan to do with it. The mode may be left out, and then it is 'r'.
The handle. Not the file, not its contents — your connection to it, held in a variable, usually called f.
What the handle knows about itself. f.closed is False while the file is open and True after close().
The three steps of every file program, in that order, without exception.
No such file, and open() raises FileNotFoundError before your program has read a thing.
A bare name means 'in the folder this program is running from'. Anything else needs the path written out.
- 1
Make a file called
notes.txtin the same folder as your program, open it, and printf.nameandf.mode.Hint · Three lines and a close(). Nothing is read yet.
- 2
Print
f.closedtwice — once beforef.close()and once after.Hint · False, then True. The handle outlives the connection.
- 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
Move
notes.txtinto a subfolder calleddataand make the program find it again.Hint · Only the string inside open() changes.
What does open('notes.txt', 'r') give back?
open('notes.txt') and open('notes.txt', 'r') are...
The file marks.txt does not exist. What does open('marks.txt', 'r') do?
After f.close(), what is f?