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

(singke) #1
repeat step 16.


  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.


Creating the /home/pi/data/friends.txt file this time was much easier than it was in the last Try It
Yourself section! By now you should have a good handle on how to open, close, read, and write data
files.


Summary


In this hour, you read about using files in Python. You saw how to open a file and how to close a file.
Also, you were introduced to Python statements and structures that allow you to read from a file and
write to a file. You got to try out both writing to a file in the dash shell and reading it, and then
writing to a file within Python and reading it. In Hour 12, “Creating Functions,” you will investigate
how to create your own Python functions, which means you are starting to move into more advanced
Python concepts.


Q&A


Q. Which directory reference is used in Table 11.2?
A. The directories shown in Table 11.2 use an absolute directory reference. Remember that an
absolute directory reference absolutely starts with the root directory. Therefore,
/home/pi/py3prog, /home/pi/temp, and /home/pi/data are all absolute
directory references.
Q. What is pickling?
A. Pickling is a method of preserving vegetables, such as cucumbers, in a salty vinegar solution.
But you are probably asking about pickling data, mentioned in Table 11.1, and not vegetables.
Pickling is a method of transforming a Python object, such as a dictionary, into a series of bytes
for storage into a file. Turning an object into a series of bytes is called serializing an object.
You need to import the pickle function to perform pickling of objects.
The advantage of pickling is that it allows you to quickly and easily handle objects. A pickled
object can be read from a file into a single variable. The disadvantage is that pickling has no
security measures built around it. Therefore, you could cause a system to be compromised by
using it.
Q. How can I keep the .write method from displaying the number of characters it has
written during the running of a Python script?
A. You can use a “cheat” method. Import the non-built-in function sys. Then before using your
.write method, redirect the terminal output by typing in the following statement:
sys.stdout = open ('/dev/null', 'w'). This sends the characters written as
output to “nowhere.” However, be very careful using a feature like this! You will also send
any error messages to “nowhere” as well!
Q. I can’t figure it out. Who are those people in the friends.txt file?
Free download pdf