As mentioned in Organization of This Chapter,
file is a built-in type in Python and the single most common way for your Python programs to read or write data. With a file object, you can read and/or write data to a file as seen by the underlying operating system. Python reacts to any I/O error related to a file object by raising an instance of built-in exception class
IOError. Errors that cause this exception include
open failing to open or create a file, calls to a method on a file object to which that method doesn’t apply (e.g., calling
write on a read-only file object, or calling
seek on a nonseekable file), and I/O errors diagnosed by a file object’s methods. This section covers file objects, as well as the important issue of making temporary files.
To create a Python file object, call the built-in
open with the following syntax:
open(filename, mode='r', bufsize=-1)
open opens the file named by plain string
filename, which denotes any path to a file.
open returns a Python file object
f, which is an instance of the built-in type
file. Currently, calling
file directly is like calling
open, but you should call
open, which may become a factory function in some future release of Python. If you explicitly pass a
open can also create
filename if the file does not already exist (depending on the value of
mode, as we’ll discuss in a moment). In other words, despite its name,
open is not just for opening existing files: it can also ...