Page 63 - Programming the Raspberry Pi Getting Started with Python
P. 63
6
Files and the Internet
Python makes it easy for your programs to use files and connect to the Internet. You can read data
from files, write data to files, and fetch content from the Internet. You can even check for new mail
and tweet—all from your program.
Files
When you run a Python program, any values you have in variables will be lost. Files provide a means
of making data more permanent.
Reading Files
Python makes reading the contents of a file extremely easy. As an example, we can convert the
Hangman program from Chapter 4 to read the list of words from a file rather than have them fixed in
the program.
First of all, start a new file in IDLE and put some words in it, one per line. Then save the file with
the name hangman_words.txt in the same directory as the Hangman program from Chapter 4
(04_08_hangman_full.py). Note that in the Save dialog you will have to change the file type to .txt
(see Figure 6-1).
Figure 6-1 Creating a text file in IDLE
Before we modify the Hangman program itself, we can just experiment with reading the file in the
Python console. Enter the following into the console:
Note that the Python console has a current directory of /home/pi, so the directory Python (or
wherever you saved the file) must be included.
Next enter the following into the Python console:
I told you it was easy! All we need to do to add this file to the Hangman program is replace the line
with the following lines: