Opening and reading a file
So far, a program's data has come from the keyboard with input, or it was written in the code itself. Most real data lives in files: the contacts in a phone, the scores of a game, the measurements a weather station has saved. A program that reads its data from a file handles ten lines or a million lines just as easily.
This course works with text files: files that hold nothing but lines of text, like the ones you'd write in a plain text editor. (A word processor's document is not one: it also stores fonts, layout and more, in a format of its own.)
open and with
Here is a file called motto.txt, with two lines of text in it:
Practice a little every day.
Small steps add up.This program opens the file, reads everything in it and prints it:
with open("motto.txt") as file:
contents = file.read()
print(contents)
Practice a little every day.
Small steps add up.open("motto.txt")opens the file with that name.- The
withstatement keeps the file open while its indented block runs, and closes it when the block ends.as filegives the open file a name. That variable is called a file handle: the program reaches the file through it. Any variable name works;fileis simply clear. - The method
read()reads the whole file and returns it as one string.
Closing files matters: an open file uses up resources, and a file that is written but never closed can lose data. With with, Python closes the file for you, even when something goes wrong inside the block.
Where the file must be
open("motto.txt") looks for the file in the folder the program runs in. On your own computer, which folder that is depends on how you start Python, which is a common source of confusion. On this site it's simple: the files a task gives are in the same folder as your program, so the file name alone is enough.
When there is no file of that name, Python stops with a FileNotFoundError that names the file it looked for. Check the spelling then: Motto.txt, motto.text and motto.txt are three different names. A later module shows how a program can handle such errors itself.
What read gives you
The string that read() returns has the line breaks of the file in it, each written \n in Python. You can do with it anything you can do with a string. The file is closed after the with block, but the string stays in its variable:
Water the plants.
Call grandma on Sunday.with open("reminder.txt") as file:
contents = file.read()
print(len(contents))
print("Sunday" in contents)
print("sunday" in contents)
42
True
FalseThe 42 characters include the two line breaks, one at the end of each line. And as always with strings, capital letters matter.
One more thing about the tasks on this site: a test can give your program a different file under the same name, so the program must really read the file. Printing text copied from the task won't pass.