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

(singke) #1

and the temperature data character string is turned into an integer on line 9.


By the Way: A Number Is a String
When reading in data from a text file in Python, numbers are not typed as numeric, such
as integer or floating point. Instead, Python assigns them the character string type
(str).
Also, when writing a number to a text file, you need to perform a conversion. A
number must be converted from its numeric type to a character string before it is
written to a text file.

The temperature is converted from Fahrenheit to Celsius on line 10 of Listing 11.14. Before the data
can be written to the new Celsius text file, it must be converted from floating point to character string,
which happens on line 12. A character string with all the needed data is created on line 12 because
the .write method can accept only one argument. Notice also on line 12 that a newline escape
sequence is added at the end of the string to act as a data separator. Now the data can be written to the
new file on line 13 in Listing 11.14.


By the Way: What Are Those Numbers?
In Listing 11.14, you can see a partial string of 8s and 9s after the .write method in
the code. This is because the .write method displays to output how many characters
it wrote to a text file or how many bytes it wrote to a binary file.

After all the data has been read from the Fahrenheit file, processed, and written out to the Celsius file,
the files should be closed. Remember that closing files is important when writing to a file, and it’s
considered good form. The files are closed on lines 22 and 23 in Listing 11.14.


So does everything work in this example? The Fahrenheit temperature data is properly read in,
converted, and written out to the Celsius file, as shown in Listing 11.15.


LISTING 11.15 The Celsius Temperature File


Click here to view code image


pi@raspberrypi ~ $ cat /home/pi/data/May2012TempC.txt
1 26.11
2 28.89
3 29.44
4 29.44
...
28 33.33
29 33.33
30 27.22
31 24.44
pi@raspberrypi ~ $

Note that each Celsius temperature has the day of the month it was recorded and is displayed in
floating-point format. Also notice that each temperature is on its own line in the text file. This is

Free download pdf