Chapter 22. File Input and Output

 

Have you ever wondered how your favorite computer game remembers the high scores, even after the computer is turned off? How about your browser remembering your favorite web sites? In this chapter, we’re going to learn how.

We have talked several times about how programs have three main aspects: input, processing, and output. Up until now, the input has mostly come directly from the user, from the keyboard and mouse. The output has been sent directly to the screen (or the speakers, in the case of sound). But sometimes we need to use input that comes from other sources. Quite often, programs need to use input that’s stored somewhere, rather than entered when the program is running. Some programs need to get their input from a file on the computer’s hard drive.

For example, if you made a game of Hangman, your program would need a word list from which to choose the secret word. That list of words would have to be stored somewhere, probably in a “word list” file that goes with the program. The program would need to open this file, read the word list, and pick a word to use.

What’s a file?

Filenames

File locations

Opening a file

Reading a file

Text files and binary files

Writing to a file

Saving your stuff in files: pickle

Game time again—Hangman

What did you learn?

Try it out