In Python, an object of the type file represents the contents of a physical file stored on a disk. A new object file may be created using the following syntax:
# creating a new file object from an existing file
myfile = open('measurement.dat','r')
The contents of the file may be accessed, for instance, with this command:
print(myfile.read())
Usage of file objects requires some care. The problem is that a file has to be closed before it can be re-read or used by other applications, which is done using the following syntax:
myfile.close() # closes the file object
It is not that simple because an exception might be triggered before the call to close is executed, which will skip the closing code (consider the following example). A simple way to make sure that a file will be properly closed is to use context managers. This construction, using the keyword with, is explained in more detail in Section 12.1.3:...