6.9 File handles
File handles provide a means of reading data directly from text files, or of writing data or logging information to files. Files are opened using the open() function:
The open([,]) function opens the file with string access mode , and returns a file handle object.
The most commonly used access modes are "r", to open a file read-only, "w", to open a file for writing, erasing any pre-existing file of the same filename, and "a", to append data to the end of a file.
Alternatively, if what is wanted is a temporary scratch space, the os.tmpfile() function should be used:
The os.tmpfile() function returns a file handle for a temporary file. The resulting file handle is open for both reading and writing.
The following methods are defined for file handles:
The close() method closes a file handle.
The dump() method stores a typeable ASCII representation of the object to a file. Note that this method has no checking for recursive hierarchical data structures.
The eof() method returns a boolean flag to indicate whether the end of a file has been reached.
The flush() method flushes any buffered data which has not yet physically been written to a file.
The getPos() method returns a file handle’s current position in a file.
The isOpen() method returns a boolean flag indicating whether a file is open.
The read() method returns the contents of a file as a string.
The readline() method returns a single line of a file as a string.
The readlines() method returns the lines of a file as a list of strings.
The setPos() method sets a file handle’s current position in a file.
The write() method writes the string to a file.