blob: a85e9242b7a766cf1cc4fa9e3c74f08f407274ac [file] [log] [blame]
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +00001:mod:`io` --- Core tools for working with streams
2=================================================
3
4.. module:: io
5 :synopsis: Core tools for working with streams.
6.. moduleauthor:: Guido van Rossum <guido@python.org>
7.. moduleauthor:: Mike Verdone <mike.verdone@gmail.com>
8.. moduleauthor:: Mark Russell <mark.russell@zen.co.uk>
Antoine Pitrouc9062ca2009-10-01 17:08:03 +00009.. moduleauthor:: Antoine Pitrou <solipsis@pitrou.net>
10.. moduleauthor:: Amaury Forgeot d'Arc <amauryfa@gmail.com>
11.. moduleauthor:: Benjamin Peterson <benjamin@python.org>
Benjamin Peterson51a37032009-01-11 19:48:15 +000012.. sectionauthor:: Benjamin Peterson <benjamin@python.org>
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +000013
Antoine Pitrouc9062ca2009-10-01 17:08:03 +000014The :mod:`io` module provides the Python interfaces to stream handling.
15Under Python 2.x, this is proposed as an alternative to the built-in
16:class:`file` object, but in Python 3.x it is the default interface to
17access files and streams.
18
19.. note::
20
21 Since this module has been designed primarily for Python 3.x, you have to
22 be aware that all uses of "bytes" in this document refer to the
23 :class:`str` type (of which :class:`bytes` is an alias), and all uses
24 of "text" refer to the :class:`unicode` type. Furthermore, those two
25 types are not interchangeable in the :mod:`io` APIs.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +000026
27At the top of the I/O hierarchy is the abstract base class :class:`IOBase`. It
28defines the basic interface to a stream. Note, however, that there is no
Mark Dickinson3e4caeb2009-02-21 20:27:01 +000029separation between reading and writing to streams; implementations are allowed
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +000030to throw an :exc:`IOError` if they do not support a given operation.
31
32Extending :class:`IOBase` is :class:`RawIOBase` which deals simply with the
33reading and writing of raw bytes to a stream. :class:`FileIO` subclasses
Benjamin Petersonad9f6292008-04-21 11:57:40 +000034:class:`RawIOBase` to provide an interface to files in the machine's
35file system.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +000036
37:class:`BufferedIOBase` deals with buffering on a raw byte stream
38(:class:`RawIOBase`). Its subclasses, :class:`BufferedWriter`,
39:class:`BufferedReader`, and :class:`BufferedRWPair` buffer streams that are
Benjamin Petersonad9f6292008-04-21 11:57:40 +000040readable, writable, and both readable and writable.
41:class:`BufferedRandom` provides a buffered interface to random access
42streams. :class:`BytesIO` is a simple stream of in-memory bytes.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +000043
Benjamin Petersonad9f6292008-04-21 11:57:40 +000044Another :class:`IOBase` subclass, :class:`TextIOBase`, deals with
45streams whose bytes represent text, and handles encoding and decoding
Antoine Pitrouc9062ca2009-10-01 17:08:03 +000046from and to :class:`unicode` strings. :class:`TextIOWrapper`, which extends
47it, is a buffered text interface to a buffered raw stream
Benjamin Petersonad9f6292008-04-21 11:57:40 +000048(:class:`BufferedIOBase`). Finally, :class:`StringIO` is an in-memory
Antoine Pitrouc9062ca2009-10-01 17:08:03 +000049stream for unicode text.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +000050
51Argument names are not part of the specification, and only the arguments of
Georg Brandl9fa61bb2009-07-26 14:19:57 +000052:func:`.open` are intended to be used as keyword arguments.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +000053
54
55Module Interface
56----------------
57
58.. data:: DEFAULT_BUFFER_SIZE
59
60 An int containing the default buffer size used by the module's buffered I/O
Georg Brandl9fa61bb2009-07-26 14:19:57 +000061 classes. :func:`.open` uses the file's blksize (as obtained by
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +000062 :func:`os.stat`) if possible.
63
Antoine Pitrouc9062ca2009-10-01 17:08:03 +000064.. function:: open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True)
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +000065
Antoine Pitrouc9062ca2009-10-01 17:08:03 +000066 Open *file* and return a corresponding stream. If the file cannot be opened,
67 an :exc:`IOError` is raised.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +000068
Antoine Pitrouc9062ca2009-10-01 17:08:03 +000069 *file* is either a string giving the name (and the path if the file isn't
70 in the current working directory) of the file to be opened or an integer
71 file descriptor of the file to be wrapped. (If a file descriptor is given,
72 for example, from :func:`os.fdopen`, it is closed when the returned I/O
73 object is closed, unless *closefd* is set to ``False``.)
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +000074
75 *mode* is an optional string that specifies the mode in which the file is
76 opened. It defaults to ``'r'`` which means open for reading in text mode.
77 Other common values are ``'w'`` for writing (truncating the file if it
78 already exists), and ``'a'`` for appending (which on *some* Unix systems,
79 means that *all* writes append to the end of the file regardless of the
80 current seek position). In text mode, if *encoding* is not specified the
81 encoding used is platform dependent. (For reading and writing raw bytes use
82 binary mode and leave *encoding* unspecified.) The available modes are:
83
84 ========= ===============================================================
85 Character Meaning
86 --------- ---------------------------------------------------------------
87 ``'r'`` open for reading (default)
88 ``'w'`` open for writing, truncating the file first
89 ``'a'`` open for writing, appending to the end of the file if it exists
90 ``'b'`` binary mode
91 ``'t'`` text mode (default)
92 ``'+'`` open a disk file for updating (reading and writing)
Benjamin Petersonad9f6292008-04-21 11:57:40 +000093 ``'U'`` universal newline mode (for backwards compatibility; should
94 not be used in new code)
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +000095 ========= ===============================================================
96
97 The default mode is ``'rt'`` (open for reading text). For binary random
98 access, the mode ``'w+b'`` opens and truncates the file to 0 bytes, while
99 ``'r+b'`` opens the file without truncation.
100
101 Python distinguishes between files opened in binary and text modes, even when
102 the underlying operating system doesn't. Files opened in binary mode
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000103 (including ``'b'`` in the *mode* argument) return contents as :class:`bytes`
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000104 objects without any decoding. In text mode (the default, or when ``'t'`` is
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000105 included in the *mode* argument), the contents of the file are returned as
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000106 :class:`unicode` strings, the bytes having been first decoded using a
107 platform-dependent encoding or using the specified *encoding* if given.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000108
109 *buffering* is an optional integer used to set the buffering policy. By
110 default full buffering is on. Pass 0 to switch buffering off (only allowed
111 in binary mode), 1 to set line buffering, and an integer > 1 for full
112 buffering.
113
114 *encoding* is the name of the encoding used to decode or encode the file.
115 This should only be used in text mode. The default encoding is platform
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000116 dependent (whatever :func:`locale.getpreferredencoding` returns), but any
117 encoding supported by Python can be used. See the :mod:`codecs` module for
118 the list of supported encodings.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000119
Benjamin Peterson53be57e2008-04-19 19:34:05 +0000120 *errors* is an optional string that specifies how encoding and decoding
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000121 errors are to be handled--this cannot be used in binary mode. Pass
122 ``'strict'`` to raise a :exc:`ValueError` exception if there is an encoding
123 error (the default of ``None`` has the same effect), or pass ``'ignore'`` to
124 ignore errors. (Note that ignoring encoding errors can lead to data loss.)
125 ``'replace'`` causes a replacement marker (such as ``'?'``) to be inserted
126 where there is malformed data. When writing, ``'xmlcharrefreplace'``
127 (replace with the appropriate XML character reference) or
128 ``'backslashreplace'`` (replace with backslashed escape sequences) can be
129 used. Any other error handling name that has been registered with
130 :func:`codecs.register_error` is also valid.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000131
132 *newline* controls how universal newlines works (it only applies to text
133 mode). It can be ``None``, ``''``, ``'\n'``, ``'\r'``, and ``'\r\n'``. It
134 works as follows:
135
136 * On input, if *newline* is ``None``, universal newlines mode is enabled.
137 Lines in the input can end in ``'\n'``, ``'\r'``, or ``'\r\n'``, and these
138 are translated into ``'\n'`` before being returned to the caller. If it is
139 ``''``, universal newline mode is enabled, but line endings are returned to
140 the caller untranslated. If it has any of the other legal values, input
141 lines are only terminated by the given string, and the line ending is
142 returned to the caller untranslated.
143
144 * On output, if *newline* is ``None``, any ``'\n'`` characters written are
145 translated to the system default line separator, :data:`os.linesep`. If
146 *newline* is ``''``, no translation takes place. If *newline* is any of
147 the other legal values, any ``'\n'`` characters written are translated to
148 the given string.
149
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000150 If *closefd* is ``False`` and a file descriptor rather than a filename was
151 given, the underlying file descriptor will be kept open when the file is
152 closed. If a filename is given *closefd* has no effect and must be ``True``
153 (the default).
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000154
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000155 The type of file object returned by the :func:`.open` function depends on the
156 mode. When :func:`.open` is used to open a file in a text mode (``'w'``,
157 ``'r'``, ``'wt'``, ``'rt'``, etc.), it returns a subclass of
158 :class:`TextIOBase` (specifically :class:`TextIOWrapper`). When used to open
159 a file in a binary mode with buffering, the returned class is a subclass of
160 :class:`BufferedIOBase`. The exact class varies: in read binary mode, it
161 returns a :class:`BufferedReader`; in write binary and append binary modes,
162 it returns a :class:`BufferedWriter`, and in read/write mode, it returns a
163 :class:`BufferedRandom`. When buffering is disabled, the raw stream, a
164 subclass of :class:`RawIOBase`, :class:`FileIO`, is returned.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000165
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000166 It is also possible to use an :class:`unicode` or :class:`bytes` string
167 as a file for both reading and writing. For :class:`unicode` strings
168 :class:`StringIO` can be used like a file opened in text mode,
169 and for :class:`bytes` a :class:`BytesIO` can be used like a
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000170 file opened in a binary mode.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000171
172
173.. exception:: BlockingIOError
174
175 Error raised when blocking would occur on a non-blocking stream. It inherits
176 :exc:`IOError`.
177
178 In addition to those of :exc:`IOError`, :exc:`BlockingIOError` has one
179 attribute:
180
181 .. attribute:: characters_written
182
183 An integer containing the number of characters written to the stream
184 before it blocked.
185
186
187.. exception:: UnsupportedOperation
188
189 An exception inheriting :exc:`IOError` and :exc:`ValueError` that is raised
190 when an unsupported operation is called on a stream.
191
192
193I/O Base Classes
194----------------
195
196.. class:: IOBase
197
198 The abstract base class for all I/O classes, acting on streams of bytes.
199 There is no public constructor.
200
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000201 This class provides empty abstract implementations for many methods
202 that derived classes can override selectively; the default
203 implementations represent a file that cannot be read, written or
204 seeked.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000205
206 Even though :class:`IOBase` does not declare :meth:`read`, :meth:`readinto`,
207 or :meth:`write` because their signatures will vary, implementations and
208 clients should consider those methods part of the interface. Also,
209 implementations may raise a :exc:`IOError` when operations they do not
210 support are called.
211
212 The basic type used for binary data read from or written to a file is
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000213 :class:`bytes` (also known as :class:`str`). :class:`bytearray`\s are
214 accepted too, and in some cases (such as :class:`readinto`) required.
215 Text I/O classes work with :class:`unicode` data.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000216
217 Note that calling any method (even inquiries) on a closed stream is
218 undefined. Implementations may raise :exc:`IOError` in this case.
219
220 IOBase (and its subclasses) support the iterator protocol, meaning that an
221 :class:`IOBase` object can be iterated over yielding the lines in a stream.
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000222 Lines are defined slightly differently depending on whether the stream is
223 a binary stream (yielding :class:`bytes`), or a text stream (yielding
224 :class:`unicode` strings). See :meth:`readline` below.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000225
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000226 IOBase is also a context manager and therefore supports the
227 :keyword:`with` statement. In this example, *file* is closed after the
228 :keyword:`with` statement's suite is finished---even if an exception occurs::
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000229
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000230 with io.open('spam.txt', 'w') as file:
231 file.write(u'Spam and eggs!')
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000232
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000233 :class:`IOBase` provides these data attributes and methods:
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000234
235 .. method:: close()
236
Amaury Forgeot d'Arc32265652008-11-20 23:34:31 +0000237 Flush and close this stream. This method has no effect if the file is
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000238 already closed. Once the file is closed, any operation on the file
Amaury Forgeot d'Arc32265652008-11-20 23:34:31 +0000239 (e.g. reading or writing) will raise an :exc:`IOError`. The internal
240 file descriptor isn't closed if *closefd* was False.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000241
242 .. attribute:: closed
243
244 True if the stream is closed.
245
246 .. method:: fileno()
247
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000248 Return the underlying file descriptor (an integer) of the stream if it
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000249 exists. An :exc:`IOError` is raised if the IO object does not use a file
250 descriptor.
251
252 .. method:: flush()
253
Benjamin Peterson53be57e2008-04-19 19:34:05 +0000254 Flush the write buffers of the stream if applicable. This does nothing
255 for read-only and non-blocking streams.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000256
257 .. method:: isatty()
258
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000259 Return ``True`` if the stream is interactive (i.e., connected to
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000260 a terminal/tty device).
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000261
262 .. method:: readable()
263
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000264 Return ``True`` if the stream can be read from. If False, :meth:`read`
265 will raise :exc:`IOError`.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000266
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000267 .. method:: readline(limit=-1)
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000268
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000269 Read and return one line from the stream. If *limit* is specified, at
270 most *limit* bytes will be read.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000271
272 The line terminator is always ``b'\n'`` for binary files; for text files,
Georg Brandl9fa61bb2009-07-26 14:19:57 +0000273 the *newlines* argument to :func:`.open` can be used to select the line
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000274 terminator(s) recognized.
275
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000276 .. method:: readlines(hint=-1)
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000277
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000278 Read and return a list of lines from the stream. *hint* can be specified
279 to control the number of lines read: no more lines will be read if the
280 total size (in bytes/characters) of all lines so far exceeds *hint*.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000281
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000282 .. method:: seek(offset, whence=SEEK_SET)
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000283
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000284 Change the stream position to the given byte *offset*. *offset* is
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000285 interpreted relative to the position indicated by *whence*. Values for
286 *whence* are:
287
Georg Brandl88ed8f22009-04-01 21:00:55 +0000288 * :data:`SEEK_SET` or ``0`` -- start of the stream (the default);
289 *offset* should be zero or positive
290 * :data:`SEEK_CUR` or ``1`` -- current stream position; *offset* may
291 be negative
292 * :data:`SEEK_END` or ``2`` -- end of the stream; *offset* is usually
293 negative
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000294
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000295 Return the new absolute position.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000296
Georg Brandl88ed8f22009-04-01 21:00:55 +0000297 .. versionadded:: 2.7
298 The ``SEEK_*`` constants
299
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000300 .. method:: seekable()
301
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000302 Return ``True`` if the stream supports random access. If ``False``,
303 :meth:`seek`, :meth:`tell` and :meth:`truncate` will raise :exc:`IOError`.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000304
305 .. method:: tell()
306
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000307 Return the current stream position.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000308
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000309 .. method:: truncate(size=None)
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000310
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000311 Truncate the file to at most *size* bytes. *size* defaults to the current
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000312 file position, as returned by :meth:`tell`.
313
314 .. method:: writable()
315
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000316 Return ``True`` if the stream supports writing. If ``False``,
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000317 :meth:`write` and :meth:`truncate` will raise :exc:`IOError`.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000318
319 .. method:: writelines(lines)
320
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000321 Write a list of lines to the stream. Line separators are not added, so it
322 is usual for each of the lines provided to have a line separator at the
323 end.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000324
325
326.. class:: RawIOBase
327
328 Base class for raw binary I/O. It inherits :class:`IOBase`. There is no
329 public constructor.
330
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000331 Raw binary I/O typically provides low-level access to an underlying OS
332 device or API, and does not try to encapsulate it in high-level primitives
333 (this is left to Buffered I/O and Text I/O, described later in this page).
334
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000335 In addition to the attributes and methods from :class:`IOBase`,
336 RawIOBase provides the following methods:
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000337
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000338 .. method:: read(n=-1)
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000339
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000340 Read up to *n* bytes from the object and return them. As a convenience,
341 if *n* is unspecified or -1, :meth:`readall` is called. Otherwise,
342 only one system call is ever made. Fewer than *n* bytes may be
343 returned if the operating system call returns fewer than *n* bytes.
344
345 If 0 bytes are returned, and *n* was not 0, this indicates end of file.
346 If the object is in non-blocking mode and no bytes are available,
347 ``None`` is returned.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000348
349 .. method:: readall()
350
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000351 Read and return all the bytes from the stream until EOF, using multiple
352 calls to the stream if necessary.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000353
354 .. method:: readinto(b)
355
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000356 Read up to len(b) bytes into bytearray *b* and return the number of bytes
357 read.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000358
359 .. method:: write(b)
360
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000361 Write the given bytes or bytearray object, *b*, to the underlying raw
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000362 stream and return the number of bytes written. This can be less than
363 ``len(b)``, depending on specifics of the underlying raw stream, and
364 especially if it is in non-blocking mode. ``None`` is returned if the
365 raw stream is set not to block and no single byte could be readily
366 written to it.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000367
368
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000369.. class:: BufferedIOBase
370
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000371 Base class for binary streams that support some kind of buffering.
372 It inherits :class:`IOBase`. There is no public constructor.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000373
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000374 The main difference with :class:`RawIOBase` is that methods :meth:`read`,
375 :meth:`readinto` and :meth:`write` will try (respectively) to read as much
376 input as requested or to consume all given output, at the expense of
377 making perhaps more than one system call.
378
379 In addition, those methods can raise :exc:`BlockingIOError` if the
380 underlying raw stream is in non-blocking mode and cannot take or give
381 enough data; unlike their :class:`RawIOBase` counterparts, they will
382 never return ``None``.
383
384 Besides, the :meth:`read` method does not have a default
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000385 implementation that defers to :meth:`readinto`.
386
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000387 A typical :class:`BufferedIOBase` implementation should not inherit from a
388 :class:`RawIOBase` implementation, but wrap one, like
389 :class:`BufferedWriter` and :class:`BufferedReader` do.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000390
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000391 :class:`BufferedIOBase` provides or overrides these members in addition to
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000392 those from :class:`IOBase`:
393
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000394 .. attribute:: raw
395
396 The underlying raw stream (a :class:`RawIOBase` instance) that
397 :class:`BufferedIOBase` deals with. This is not part of the
398 :class:`BufferedIOBase` API and may not exist on some implementations.
399
400 .. method:: detach()
401
402 Separate the underlying raw stream from the buffer and return it.
403
404 After the raw stream has been detached, the buffer is in an unusable
405 state.
406
407 Some buffers, like :class:`BytesIO`, do not have the concept of a single
408 raw stream to return from this method. They raise
409 :exc:`UnsupportedOperation`.
410
411 .. versionadded:: 2.7
412
413 .. method:: read(n=-1)
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000414
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000415 Read and return up to *n* bytes. If the argument is omitted, ``None``, or
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000416 negative, data is read and returned until EOF is reached. An empty bytes
417 object is returned if the stream is already at EOF.
418
419 If the argument is positive, and the underlying raw stream is not
420 interactive, multiple raw reads may be issued to satisfy the byte count
421 (unless EOF is reached first). But for interactive raw streams, at most
422 one raw read will be issued, and a short result does not imply that EOF is
423 imminent.
424
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000425 A :exc:`BlockingIOError` is raised if the underlying raw stream is in
426 non blocking-mode, and has no data available at the moment.
427
428 .. method:: read1(n=-1)
429
430 Read and return up to *n* bytes, with at most one call to the underlying
431 raw stream's :meth:`~RawIOBase.read` method. This can be useful if you
432 are implementing your own buffering on top of a :class:`BufferedIOBase`
433 object.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000434
435 .. method:: readinto(b)
436
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000437 Read up to len(b) bytes into bytearray *b* and return the number of bytes
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000438 read.
439
440 Like :meth:`read`, multiple reads may be issued to the underlying raw
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000441 stream, unless the latter is 'interactive'.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000442
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000443 A :exc:`BlockingIOError` is raised if the underlying raw stream is in
444 non blocking-mode, and has no data available at the moment.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000445
446 .. method:: write(b)
447
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000448 Write the given bytes or bytearray object, *b* and return the number
449 of bytes written (never less than ``len(b)``, since if the write fails
450 an :exc:`IOError` will be raised). Depending on the actual
451 implementation, these bytes may be readily written to the underlying
452 stream, or held in a buffer for performance and latency reasons.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000453
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000454 When in non-blocking mode, a :exc:`BlockingIOError` is raised if the
455 data needed to be written to the raw stream but it couldn't accept
456 all the data without blocking.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000457
458
Benjamin Petersonb6c7beb2009-01-19 16:17:54 +0000459Raw File I/O
460------------
461
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000462.. class:: FileIO(name, mode='r', closefd=True)
Benjamin Petersonb6c7beb2009-01-19 16:17:54 +0000463
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000464 :class:`FileIO` represents an OS-level file containing bytes data.
465 It implements the :class:`RawIOBase` interface (and therefore the
466 :class:`IOBase` interface, too).
467
468 The *name* can be one of two things:
469
470 * a string representing the path to the file which will be opened;
471 * an integer representing the number of an existing OS-level file descriptor
472 to which the resulting :class:`FileIO` object will give access.
Benjamin Petersonb6c7beb2009-01-19 16:17:54 +0000473
474 The *mode* can be ``'r'``, ``'w'`` or ``'a'`` for reading (default), writing,
475 or appending. The file will be created if it doesn't exist when opened for
476 writing or appending; it will be truncated when opened for writing. Add a
477 ``'+'`` to the mode to allow simultaneous reading and writing.
478
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000479 The :meth:`read` (when called with a positive argument), :meth:`readinto`
480 and :meth:`write` methods on this class will only make one system call.
481
Benjamin Petersonb6c7beb2009-01-19 16:17:54 +0000482 In addition to the attributes and methods from :class:`IOBase` and
483 :class:`RawIOBase`, :class:`FileIO` provides the following data
484 attributes and methods:
485
486 .. attribute:: mode
487
488 The mode as given in the constructor.
489
490 .. attribute:: name
491
492 The file name. This is the file descriptor of the file when no name is
493 given in the constructor.
494
Benjamin Petersonb6c7beb2009-01-19 16:17:54 +0000495
496Buffered Streams
497----------------
498
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000499In many situations, buffered I/O streams will provide higher performance
500(bandwidth and latency) than raw I/O streams. Their API is also more usable.
501
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000502.. class:: BytesIO([initial_bytes])
503
504 A stream implementation using an in-memory bytes buffer. It inherits
505 :class:`BufferedIOBase`.
506
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000507 The argument *initial_bytes* is an optional initial :class:`bytes`.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000508
509 :class:`BytesIO` provides or overrides these methods in addition to those
510 from :class:`BufferedIOBase` and :class:`IOBase`:
511
512 .. method:: getvalue()
513
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000514 Return ``bytes`` containing the entire contents of the buffer.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000515
516 .. method:: read1()
517
Benjamin Peterson53be57e2008-04-19 19:34:05 +0000518 In :class:`BytesIO`, this is the same as :meth:`read`.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000519
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000520 .. method:: truncate([size])
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000521
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000522 Truncate the buffer to at most *size* bytes. *size* defaults to the
523 current stream position, as returned by :meth:`tell`.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000524
525
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000526.. class:: BufferedReader(raw, buffer_size=DEFAULT_BUFFER_SIZE)
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000527
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000528 A buffer providing higher-level access to a readable, sequential
529 :class:`RawIOBase` object. It inherits :class:`BufferedIOBase`.
530 When reading data from this object, a larger amount of data may be
531 requested from the underlying raw stream, and kept in an internal buffer.
532 The buffered data can then be returned directly on subsequent reads.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000533
534 The constructor creates a :class:`BufferedReader` for the given readable
535 *raw* stream and *buffer_size*. If *buffer_size* is omitted,
536 :data:`DEFAULT_BUFFER_SIZE` is used.
537
538 :class:`BufferedReader` provides or overrides these methods in addition to
539 those from :class:`BufferedIOBase` and :class:`IOBase`:
540
541 .. method:: peek([n])
542
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000543 Return bytes from the stream without advancing the position. At most one
544 single read on the raw stream is done to satisfy the call. The number of
545 bytes returned may be less or more than requested.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000546
547 .. method:: read([n])
548
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000549 Read and return *n* bytes, or if *n* is not given or negative, until EOF
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000550 or if the read call would block in non-blocking mode.
551
552 .. method:: read1(n)
553
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000554 Read and return up to *n* bytes with only one call on the raw stream. If
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000555 at least one byte is buffered, only buffered bytes are returned.
556 Otherwise, one raw stream read call is made.
557
558
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000559.. class:: BufferedWriter(raw, buffer_size=DEFAULT_BUFFER_SIZE)
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000560
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000561 A buffer providing higher-level access to a writeable, sequential
562 :class:`RawIOBase` object. It inherits :class:`BufferedIOBase`.
563 When writing to this object, data is normally held into an internal
564 buffer. The buffer will be written out to the underlying :class:`RawIOBase`
565 object under various conditions, including:
566
567 * when the buffer gets too small for all pending data;
568 * when :meth:`flush()` is called;
569 * when a :meth:`seek()` is requested (for :class:`BufferedRandom` objects);
570 * when the :class:`BufferedWriter` object is closed or destroyed.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000571
572 The constructor creates a :class:`BufferedWriter` for the given writeable
573 *raw* stream. If the *buffer_size* is not given, it defaults to
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000574 :data:`DEFAULT_BUFFER_SIZE`.
575
576 A third argument, *max_buffer_size*, is supported, but unused and deprecated.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000577
578 :class:`BufferedWriter` provides or overrides these methods in addition to
579 those from :class:`BufferedIOBase` and :class:`IOBase`:
580
581 .. method:: flush()
582
583 Force bytes held in the buffer into the raw stream. A
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000584 :exc:`BlockingIOError` should be raised if the raw stream blocks.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000585
586 .. method:: write(b)
587
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000588 Write the bytes or bytearray object, *b* and return the number of bytes
589 written. When in non-blocking mode, a :exc:`BlockingIOError` is raised
590 if the buffer needs to be written out but the raw stream blocks.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000591
592
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000593.. class:: BufferedRWPair(reader, writer, buffer_size=DEFAULT_BUFFER_SIZE)
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000594
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000595 A buffered I/O object giving a combined, higher-level access to two
596 sequential :class:`RawIOBase` objects: one readable, the other writeable.
597 It is useful for pairs of unidirectional communication channels
598 (pipes, for instance). It inherits :class:`BufferedIOBase`.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000599
600 *reader* and *writer* are :class:`RawIOBase` objects that are readable and
601 writeable respectively. If the *buffer_size* is omitted it defaults to
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000602 :data:`DEFAULT_BUFFER_SIZE`.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000603
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000604 A fourth argument, *max_buffer_size*, is supported, but unused and
605 deprecated.
606
607 :class:`BufferedRWPair` implements all of :class:`BufferedIOBase`\'s methods
608 except for :meth:`~BufferedIOBase.detach`, which raises
609 :exc:`UnsupportedOperation`.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000610
611
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000612.. class:: BufferedRandom(raw, buffer_size=DEFAULT_BUFFER_SIZE)
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000613
614 A buffered interface to random access streams. It inherits
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000615 :class:`BufferedReader` and :class:`BufferedWriter`, and further supports
616 :meth:`seek` and :meth:`tell` functionality.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000617
618 The constructor creates a reader and writer for a seekable raw stream, given
619 in the first argument. If the *buffer_size* is omitted it defaults to
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000620 :data:`DEFAULT_BUFFER_SIZE`.
621
622 A third argument, *max_buffer_size*, is supported, but unused and deprecated.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000623
624 :class:`BufferedRandom` is capable of anything :class:`BufferedReader` or
625 :class:`BufferedWriter` can do.
626
627
628Text I/O
629--------
630
631.. class:: TextIOBase
632
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000633 Base class for text streams. This class provides an unicode character
634 and line based interface to stream I/O. There is no :meth:`readinto`
635 method because Python's :class:`unicode` strings are immutable.
636 It inherits :class:`IOBase`. There is no public constructor.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000637
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000638 :class:`TextIOBase` provides or overrides these data attributes and
639 methods in addition to those from :class:`IOBase`:
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000640
641 .. attribute:: encoding
642
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000643 The name of the encoding used to decode the stream's bytes into
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000644 strings, and to encode strings into bytes.
645
Antoine Pitrou19690592009-06-12 20:14:08 +0000646 .. attribute:: errors
647
648 The error setting of the decoder or encoder.
649
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000650 .. attribute:: newlines
651
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000652 A string, a tuple of strings, or ``None``, indicating the newlines
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000653 translated so far. Depending on the implementation and the initial
654 constructor flags, this may not be available.
655
656 .. attribute:: buffer
657
658 The underlying binary buffer (a :class:`BufferedIOBase` instance) that
659 :class:`TextIOBase` deals with. This is not part of the
660 :class:`TextIOBase` API and may not exist on some implementations.
661
662 .. method:: detach()
663
664 Separate the underlying binary buffer from the :class:`TextIOBase` and
665 return it.
666
667 After the underlying buffer has been detached, the :class:`TextIOBase` is
668 in an unusable state.
669
670 Some :class:`TextIOBase` implementations, like :class:`StringIO`, may not
671 have the concept of an underlying buffer and calling this method will
672 raise :exc:`UnsupportedOperation`.
673
674 .. versionadded:: 2.7
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000675
676 .. method:: read(n)
677
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000678 Read and return at most *n* characters from the stream as a single
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000679 :class:`unicode`. If *n* is negative or ``None``, reads until EOF.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000680
681 .. method:: readline()
682
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000683 Read until newline or EOF and return a single ``unicode``. If the
684 stream is already at EOF, an empty string is returned.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000685
686 .. method:: write(s)
687
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000688 Write the :class:`unicode` string *s* to the stream and return the
689 number of characters written.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000690
691
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000692.. class:: TextIOWrapper(buffer, encoding=None, errors=None, newline=None, line_buffering=False)
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000693
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000694 A buffered text stream over a :class:`BufferedIOBase` binary stream.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000695 It inherits :class:`TextIOBase`.
696
697 *encoding* gives the name of the encoding that the stream will be decoded or
698 encoded with. It defaults to :func:`locale.getpreferredencoding`.
699
Benjamin Peterson53be57e2008-04-19 19:34:05 +0000700 *errors* is an optional string that specifies how encoding and decoding
701 errors are to be handled. Pass ``'strict'`` to raise a :exc:`ValueError`
702 exception if there is an encoding error (the default of ``None`` has the same
703 effect), or pass ``'ignore'`` to ignore errors. (Note that ignoring encoding
704 errors can lead to data loss.) ``'replace'`` causes a replacement marker
Benjamin Petersona7d09032008-04-19 19:47:34 +0000705 (such as ``'?'``) to be inserted where there is malformed data. When
706 writing, ``'xmlcharrefreplace'`` (replace with the appropriate XML character
707 reference) or ``'backslashreplace'`` (replace with backslashed escape
708 sequences) can be used. Any other error handling name that has been
709 registered with :func:`codecs.register_error` is also valid.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000710
711 *newline* can be ``None``, ``''``, ``'\n'``, ``'\r'``, or ``'\r\n'``. It
712 controls the handling of line endings. If it is ``None``, universal newlines
713 is enabled. With this enabled, on input, the lines endings ``'\n'``,
714 ``'\r'``, or ``'\r\n'`` are translated to ``'\n'`` before being returned to
715 the caller. Conversely, on output, ``'\n'`` is translated to the system
Mark Dickinson3e4caeb2009-02-21 20:27:01 +0000716 default line separator, :data:`os.linesep`. If *newline* is any other of its
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000717 legal values, that newline becomes the newline when the file is read and it
718 is returned untranslated. On output, ``'\n'`` is converted to the *newline*.
719
720 If *line_buffering* is ``True``, :meth:`flush` is implied when a call to
721 write contains a newline character.
722
Antoine Pitrou19690592009-06-12 20:14:08 +0000723 :class:`TextIOWrapper` provides one attribute in addition to those of
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000724 :class:`TextIOBase` and its parents:
725
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000726 .. attribute:: line_buffering
727
728 Whether line buffering is enabled.
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000729
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000730
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000731.. class:: StringIO(initial_value=u'', newline=None)
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000732
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000733 An in-memory stream for unicode text. It inherits :class:`TextIOWrapper`.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000734
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000735 The initial value of the buffer (an empty unicode string by default) can
736 be set by providing *initial_value*. The *newline* argument works like
737 that of :class:`TextIOWrapper`. The default is to do no newline
738 translation.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000739
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000740 :class:`StringIO` provides this method in addition to those from
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000741 :class:`TextIOWrapper` and its parents:
742
743 .. method:: getvalue()
744
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000745 Return a ``unicode`` containing the entire contents of the buffer at any
746 time before the :class:`StringIO` object's :meth:`close` method is
747 called.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000748
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000749 Example usage::
750
751 import io
752
753 output = io.StringIO()
754 output.write(u'First line.\n')
755 output.write(u'Second line.\n')
756
757 # Retrieve file contents -- this will be
758 # u'First line.\nSecond line.\n'
759 contents = output.getvalue()
760
761 # Close object and discard memory buffer --
762 # .getvalue() will now raise an exception.
763 output.close()
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000764
765.. class:: IncrementalNewlineDecoder
766
767 A helper codec that decodes newlines for universal newlines mode. It
768 inherits :class:`codecs.IncrementalDecoder`.
769