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

(singke) #1
TABLE 11.6 File Object Methods for File Attributes

Going back to the example used in Listing 11.3, you can see in Listing 11.4 these file object methods
being used to determine current file attributes.


LISTING 11.4 Determining File Attributes


Click here to view code image


...
>>> os.getcwd()
'/home/pi/data'
>>> temp_data_file = open('May2012TempF.txt', 'r')
>>>
>>> temp_data_file.closed
False
>>> temp_data_file.mode
'r'
>>> temp_data_file.name
'May2012TempF.txt'
>>>

Notice that the result of the .name method returns the name used in the open function. In this case,
the file name used does not need to include an absolute directory reference. This is because the file is
located in the present working directory. In Listing 11.5, the file to be opened is not in the present
working directory, so a slight change has to be made in the open argument.


LISTING 11.5 Opening a File Using Absolute Directory Reference


Click here to view code image


...
>>> os.getcwd()
'/home/pi'
>>> temp_data_file = open('/home/pi/data/May2012TempF.txt', 'r')
>>> temp_data_file.name
'/home/pi/data/May2012TempF.txt'
>>>

Notice in Listing 11.5, that the absolute directory reference is used for the file name in the open
function. When this is done, the file object method .name returns the entire file’s name and its
directory location. Therefore, you can see that these file object methods are based on the attributes
used in the open function.

Free download pdf