15.2. io — Core tools for working with streams — Python v2.7 documentation (original) (raw)

Open file and return a corresponding stream. If the file cannot be opened, an IOError is raised.

file is either a string giving the name (and the path if the file isn’t in the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. (If a file descriptor is given, for example, from os.fdopen(), it is closed when the returned I/O object is closed, unless closefd is set to False.)

mode is an optional string that specifies the mode in which the file is opened. It defaults to 'r' which means open for reading in text mode. Other common values are 'w' for writing (truncating the file if it already exists), and 'a' for appending (which on some Unix systems, means that all writes append to the end of the file regardless of the current seek position). In text mode, if encoding is not specified the encoding used is platform dependent. (For reading and writing raw bytes use binary mode and leave encoding unspecified.) The available modes are:

Character Meaning
'r' open for reading (default)
'w' open for writing, truncating the file first
'a' open for writing, appending to the end of the file if it exists
'b' binary mode
't' text mode (default)
'+' open a disk file for updating (reading and writing)
'U' universal newline mode (for backwards compatibility; should not be used in new code)

The default mode is 'rt' (open for reading text). For binary random access, the mode 'w+b' opens and truncates the file to 0 bytes, while'r+b' opens the file without truncation.

Python distinguishes between files opened in binary and text modes, even when the underlying operating system doesn’t. Files opened in binary mode (including 'b' in the mode argument) return contents as bytesobjects without any decoding. In text mode (the default, or when 't' is included in the mode argument), the contents of the file are returned asunicode strings, the bytes having been first decoded using a platform-dependent encoding or using the specified encoding if given.

buffering is an optional integer used to set the buffering policy. Pass 0 to switch buffering off (only allowed in binary mode), 1 to select line buffering (only usable in text mode), and an integer > 1 to indicate the size of a fixed-size chunk buffer. When no buffering argument is given, the default buffering policy works as follows:

encoding is the name of the encoding used to decode or encode the file. This should only be used in text mode. The default encoding is platform dependent (whatever locale.getpreferredencoding() returns), but any encoding supported by Python can be used. See the codecs module for the list of supported encodings.

errors is an optional string that specifies how encoding and decoding errors are to be handled–this cannot be used in binary mode. Pass'strict' to raise a ValueError exception if there is an encoding error (the default of None has the same effect), or pass 'ignore' to ignore errors. (Note that ignoring encoding errors can lead to data loss.)'replace' causes a replacement marker (such as '?') to be inserted where there is malformed data. When writing, 'xmlcharrefreplace'(replace with the appropriate XML character reference) or'backslashreplace' (replace with backslashed escape sequences) can be used. Any other error handling name that has been registered withcodecs.register_error() is also valid.

newline controls how universal newlines works (it only applies to text mode). It can be None, '', '\n', '\r', and '\r\n'. It works as follows:

If closefd is False and a file descriptor rather than a filename was given, the underlying file descriptor will be kept open when the file is closed. If a filename is given closefd has no effect and must be True(the default).

The type of file object returned by the open() function depends on the mode. When open() is used to open a file in a text mode ('w','r', 'wt', 'rt', etc.), it returns a subclass ofTextIOBase (specifically TextIOWrapper). When used to open a file in a binary mode with buffering, the returned class is a subclass ofBufferedIOBase. The exact class varies: in read binary mode, it returns a BufferedReader; in write binary and append binary modes, it returns a BufferedWriter, and in read/write mode, it returns aBufferedRandom. When buffering is disabled, the raw stream, a subclass of RawIOBase, FileIO, is returned.

It is also possible to use an unicode or bytes string as a file for both reading and writing. For unicode stringsStringIO can be used like a file opened in text mode, and for bytes a BytesIO can be used like a file opened in a binary mode.