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

(singke) #1

LISTING 11.2 Using the os Function


Click here to view code image


1: pi@raspberrypi ~ $ pwd
2: /home/pi
3: pi@raspberrypi ~ $ python3
4: Python 3.2.3 (default, Jan 28 2013, 11:47:15)
5: [GCC 4.6.3] on linux2
6: Type "help", "copyright", "credits" or "license" for more information.
7: >>>
8: >>> import os
9: >>> os.getcwd()
10: '/home/pi'
11: >>> os.mkdir('MyNewDir')
12: >>> os.chdir('MyNewDir')
13: >>> os.getcwd()
14: '/home/pi/MyNewDir'
15: >>>

Handling these methods within Python allows you to manage directories from within your scripts.
You can create and use files within these directories.


Opening a File


To access a file in a Python script, you use the built-in open function. This is the basic syntax for
using this function:


Click here to view code image


filename_variable = open (filename, options)

Several options can be used in the open function, as shown in Table 11.4.


TABLE 11.4 open Function Options

Which options are used typically depends on which file type (see Table 11.1) you are opening. For
learning purposes here, the focus is on the mode option of the open function.


Designating the Open Mode


For the mode option in the open function, several modes can be designated, as shown in Table 11.5.

Free download pdf