Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1

  1. You will create a file object and open your friends.txt file. Type
    my_friends_file = open ('friends.txt','r') at the prompt and
    press Enter.

  2. Create a for loop to read the friends file you just opened, line by line, by typing in
    for my_friend in my_friends_file: and pressing Enter. Wait a minute!
    Where is the range statement? Don’t worry. You can elegantly loop through the
    friends.txt file by using this for loop structure. Just wait and see.

  3. Press the Tab key one time and then type print (my_friend, end=' ').
    That’s right! There is no readline method included in this loop.

  4. To see this nice little loop read through the friends.txt file, press the Enter key
    two times. You should see results similar to the output in Listing 11.11.


LISTING 11.11 Reading friends.txt Line by Line

Chris
Zach
Karl
Zoe
Simon
John
Anton
>>>


  1. Press Ctrl+D to exit the Python interactive shell.

  2. If you want to power down your Raspberry Pi now, type sudo poweroff and
    press the Enter key.


The new style of for loop you used in these steps does not require any read methods. This is
because you can use a file object variable as a method for iterating through the file.


One item that has been very sloppily handled so far in this book is closing files. Notice in step 25 that
you just quit out of the Python interactive shell, without doing any proper file closure. In the next
section, you will learn how to properly close a file.


Closing a File


When a file is opened in almost any program, it is considered good form to close it before you exit
that program. This is true in Python scripting as well. The general syntax for closing an opened file is:


filename_variable.close ()

In Listing 11.12, the temperature file is opened and then closed. Whether or not the file is opened is
tested two times by the .closed method.


LISTING 11.12 Closing the Temperature File


Click here to view code image

Free download pdf