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

(singke) #1

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

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

  3. At the shell prompt, type mkdir /home/pi/data and press the Enter key. The
    shell command creates the data subdirectory needed for storing your permanent
    Python data files.

  4. You need to create a new blank file in your new directory. Do this by typing
    touch/home/pi/data/friends.txt at the shell prompt and pressing Enter.

  5. Double-check that the file is there by typing ls data and pressing Enter. You
    should see the file friends.txt listed. Notice that when you enter the ls
    command, you use a relative directory reference of data instead of an absolute
    directory reference of /home/pi/data.

  6. Using a shell command in order to write records to the friends.txt file, type
    echo "Chris" > /home/pi/data/friends.txt and press Enter.

  7. Another shell command will be used to append another friend to the bottom of the
    file, friends.txt. Type echo "Zach" >> /home/pi/data/friends.txt
    and press Enter. (Note that two greater-than signs (>>) are used this time.)

  8. Type echo "Karl" >> /home/pi/data/friends.txt and press Enter.

  9. Type echo "Zoe" >> /home/pi/data/friends.txt and press Enter.

  10. Type echo "Simon" >> /home/pi/data/friends.txt and press
    Enter. (Yes, this is tedious. But it will help you appreciate writing to a file later this
    hour all the more.)

  11. Type echo "John" >> /home/pi/data/friends.txt and press Enter.

  12. Type echo "Anton" >> /home/pi/data/friends.txt and press
    Enter. (Do you recognize these names yet?)

  13. Finally, you are all done creating your friends.txt file! Take a look at its contents by
    typing cat data/friends.txt and pressing Enter. Don’t worry if there are
    typos in your file. Just note them, so they won’t cause you confusion later on in this
    section.

  14. Type pwd and press Enter. Take note of your present working directory.

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

  16. At the Python interactive shell prompt, >>>, type import os and press Enter to
    import the os function into your Python shell.

  17. Type os.getcwd() and press Enter. You should see the same present working
    directory displayed that you saw in step 15.

  18. To move down into the data subdirectory, type os.chdir('data') and press
    Enter.

  19. Type os.listdir() and press Enter. Do you see the file friends.txt listed
    in the output of this command? You should see it!

Free download pdf