>>> temp_data_file = open('/home/pi/data/May2012TempF.txt','r')
>>> temp_data_file.closed
False
>>> temp_data_file.close() # Close the temperature data file.
>>> temp_data_file.closed
True
>>>
Python automatically closes a file if its file name variable is reassigned to another file. However,
when you’re writing to a file, closing a file can be critical. This is due to the fact that the operating
system buffers the write methods in memory. The data is written to the file only when the buffer
reaches a certain level. When a file is closed in Python, the buffer in memory is automatically written
to the file, whether it is full or not. Not properly closing a file could leave your file’s data in a very
interesting state!
You can see why it is considered good form to properly close a file, especially if it is being written
to. This leads to the next topic of this hour: writing to a file.
Writing to a File
A file can be opened for writing only, or it can be opened to be read and written. The open mode for
writing a text file is either w or a, depending on whether you want to create a new file or append to
an old one. Adding a + at the end of the w or a open mode allows you to both read and write to the
file.
Creating and Writing to a New File
Listing 11.13 shows a new text file opened using the open function. In this case, a new file is needed
to hold new temperature data.
LISTING 11.13 Opening a File for Creation and Writing
Click here to view code image
pi@raspberrypi ~ $ ls /home/pi/data
friends.txt May2012TempF.txt
pi@raspberrypi ~ $
pi@raspberrypi ~ $ python3
Python 3.2.3 (default, Jan 28 2013, 11:47:15)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> import os
>>> os.listdir('/home/pi/data')
['friends.txt', 'May2012TempF.txt']
>>>
>>> ctemp_data_file = open('/home/pi/data/May2012TempC.txt', 'w')
>>>
>>> os.listdir('/home/pi/data')
['friends.txt', 'May2012TempC.txt', 'May2012TempF.txt']
>>>
You can see in Listing 11.13 that the file May2012TempC.txt was nonexistent before the open