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

(singke) #1

function was used. Once the file was opened, using the w mode, the text file was created.


Watch Out!: Write Mode Removes
Keep in mind that if a file is opened in write mode, w, using the open function, and it
already exists, the entire file’s contents will be erased! To preserve a preexisting file,
use the append, a, mode to open a file. See the next section in this hour, “Writing to a
Preexisting File,” for how to accomplish appending to a file.

Once the file is properly opened in the correct mode, you can begin to write data to it by using the
.write method. Again using the example from Hour 9, “Dictionaries and Sets,” now you can read a
file containing temperatures in Fahrenheit, convert the temperatures to Celsius, and then write the data
to a new file.


In Listing 11.14, the Fahrenheit file May2012TempF.txt is open for reading, so the temperatures
in it can be converted to Celsius. The Celsius file May2012TempC.txt is opened for writing.
Included on line 5 is a for loop for reading the Fahrenheit temperatures from the Fahrenheit file.
Notice that the for loop is the more elegant version of a file reading loop that you used in the Try It
Yourself section of this hour.


LISTING 11.14 Writing to the Celsius Temperature File


Click here to view code image


1: >>> ftemp_data_file = open ('/home/pi/data/May2012TempF.txt', 'r')
2: >>> ctemp_data_file = open ('/home/pi/data/May2012TempC.txt', 'w')
3: >>>
4: >>> date_count = 0
5: >>> for ftemp_data in ftemp_data_file:
6: ... ftemp_data = ftemp_data.rstrip('\n')
7: ... ftemp_data = ftemp_data[2:len(ftemp_data)]
8: ... ftemp_data = ftemp_data.lstrip(' ')
9: ... ftemp_data = int(ftemp_data)
10: ... ctemp_data = round((ftemp_data - 32) * 5/9, 2)
11: ... date_count += 1
12: ... ctemp_data = str(date_count) + ' ' + str(ctemp_data) + '\n'
13: ... ctemp_data_file.write(ctemp_data)
14: ...
15: 8
16: 8
17: 8
18: ...
19: 9
20: 9
21: 9
22: >>> ftemp_data_file.close()
23: >>> ctemp_data_file.close()

After the Fahrenheit temperature is read into the variable ftemp_data, some processing is needed
to pull out the temperature from the read-in data. First, on line 6, the newline escape sequence is
stripped off. On line 7, the temperature is obtained using string slicing. (You learned about string
slicing in Hour 10.) Before calculations start, any preceding blank spaces are stripped off in line 8,

Free download pdf