File Objects

As discussed earlier in this chapter, file is a built-in type in Python. 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, calling 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 non-seekable file), and I/O errors diagnosed by a file object’s methods. This section documents file objects, as well as some auxiliary modules that help you access and deal with their contents.

Creating a File Object with open

You normally create a Python file object with the built-in open, which has the following syntax:


open opens the file named by filename, which must be a string that denotes any path to a file. open returns a Python file object, which is an instance of the built-in type file. Calling file is just like calling open, but file was first introduced in Python 2.2. If you explicitly pass a mode string, 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 limited to opening existing files, but is also able to create new ones if needed.

File mode

mode is a string that denotes how the file ...

Get Python in a Nutshell now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.