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

(singke) #1

because the newline \n escape sequence was tacked onto the end of each Celsius temperature data
string in Listing 11.14, line 12.


Writing to a Preexisting File


You tell Python that written data will be appended to a preexisting file via the open function. After
that, writing data to a preexisting file using the .write method is no different than using the
.write method for writing data to a new file.


In Listing 11.16, the Celsius temperature file is opened. This file was just filled with data in the last
section of this hour.


LISTING 11.16 Opening a File to Append to It


Click here to view code image


>>> ctemp_data_file = open ('/home/pi/data/May2012TempC.txt', 'a')
>>>

The open statement’s mode setting keeps the file’s data from being overwritten. The mode is set to
a, which does two things. First, it preserves the current data. Second, the file pointer is set to point at
the end of the file. Thus, any .write methods that occur, start writing at the file’s bottom, and no
data is lost.


Try It Yourself: Open a File and Write to It
In the last Try it Yourself, you created a file outside Python. In the following steps, you
get to create a file inside Python! Before you can complete these steps, you need to
have completed the last Try It Yourself in this hour. If you haven’t, go back and do it
now! When you’re ready, follow these steps:


  1. If you have not already done so, power up your Raspberry Pi and log in to the
    system.

  2. If you do not have the LXDE GUI started automatically at boot, start it now by typing
    startx and pressing Enter.

  3. Open the LXTerminal by double-clicking the LXTerminal icon.

  4. Open the Python interactive shell by typing python3 at the shell prompt and
    pressing Enter.

  5. To open the file needed, at the Python interactive shell prompt, >>>, type
    my_friends_file = open
    ('/home/pi/data/friends.txt','w+') and press Enter. Wait! Won’t
    this delete the contents of the friends.txt file you created in the last Try It
    Yourself section? Yes, you are correct. Opening the file using the w mode will
    indeed clear out the friends.txt file. But, don’t worry. You will be rebuilding
    it. This is why you use the +. After you fill the file with data, you will be reading it.

  6. Create a for loop to create the friends file, using keyboard input by typing for
    friend_count in range(1, 7+1): and pressing Enter.

Free download pdf