blob: c8ff5b826d8b3f10df0ea652250923d4c5288c79 [file] [log] [blame]
Georg Brandl014197c2008-04-09 18:40:51 +00001:mod:`io` --- Core tools for working with streams
2=================================================
3
4.. module:: io
5 :synopsis: Core tools for working with streams.
Terry Jan Reedyfa089b92016-06-11 15:02:54 -04006
Georg Brandl014197c2008-04-09 18:40:51 +00007.. moduleauthor:: Guido van Rossum <guido@python.org>
8.. moduleauthor:: Mike Verdone <mike.verdone@gmail.com>
9.. moduleauthor:: Mark Russell <mark.russell@zen.co.uk>
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000010.. moduleauthor:: Antoine Pitrou <solipsis@pitrou.net>
11.. moduleauthor:: Amaury Forgeot d'Arc <amauryfa@gmail.com>
Benjamin Petersonef9f2bd2009-05-01 20:45:43 +000012.. moduleauthor:: Benjamin Peterson <benjamin@python.org>
Benjamin Peterson058e31e2009-01-16 03:54:08 +000013.. sectionauthor:: Benjamin Peterson <benjamin@python.org>
Georg Brandl014197c2008-04-09 18:40:51 +000014
Terry Jan Reedyfa089b92016-06-11 15:02:54 -040015**Source code:** :source:`Lib/io.py`
16
17--------------
18
Benjamin Peterson6b4fa772010-08-30 13:19:53 +000019.. _io-overview:
20
Antoine Pitroub530e142010-08-30 12:41:00 +000021Overview
22--------
Georg Brandl014197c2008-04-09 18:40:51 +000023
R David Murray9f0c9402012-08-17 20:33:54 -040024.. index::
25 single: file object; io module
26
27The :mod:`io` module provides Python's main facilities for dealing with various
28types of I/O. There are three main types of I/O: *text I/O*, *binary I/O*
29and *raw I/O*. These are generic categories, and various backing stores can
30be used for each of them. A concrete object belonging to any of these
31categories is called a :term:`file object`. Other common terms are *stream*
32and *file-like object*.
Georg Brandl014197c2008-04-09 18:40:51 +000033
Antoine Pitroub530e142010-08-30 12:41:00 +000034Independently of its category, each concrete stream object will also have
Benjamin Peterson6b4fa772010-08-30 13:19:53 +000035various capabilities: it can be read-only, write-only, or read-write. It can
36also allow arbitrary random access (seeking forwards or backwards to any
37location), or only sequential access (for example in the case of a socket or
38pipe).
Georg Brandl014197c2008-04-09 18:40:51 +000039
Antoine Pitroub530e142010-08-30 12:41:00 +000040All streams are careful about the type of data you give to them. For example
41giving a :class:`str` object to the ``write()`` method of a binary stream
42will raise a ``TypeError``. So will giving a :class:`bytes` object to the
43``write()`` method of a text stream.
Georg Brandl014197c2008-04-09 18:40:51 +000044
Antoine Pitroua787b652011-10-12 19:02:52 +020045.. versionchanged:: 3.3
Eli Benderskyf877a7c2012-07-14 21:22:25 +030046 Operations that used to raise :exc:`IOError` now raise :exc:`OSError`, since
47 :exc:`IOError` is now an alias of :exc:`OSError`.
Antoine Pitroua787b652011-10-12 19:02:52 +020048
Benjamin Peterson6b4fa772010-08-30 13:19:53 +000049
Antoine Pitroub530e142010-08-30 12:41:00 +000050Text I/O
51^^^^^^^^
Georg Brandl014197c2008-04-09 18:40:51 +000052
Benjamin Peterson6b4fa772010-08-30 13:19:53 +000053Text I/O expects and produces :class:`str` objects. This means that whenever
54the backing store is natively made of bytes (such as in the case of a file),
55encoding and decoding of data is made transparently as well as optional
56translation of platform-specific newline characters.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +000057
Benjamin Peterson6b4fa772010-08-30 13:19:53 +000058The easiest way to create a text stream is with :meth:`open()`, optionally
59specifying an encoding::
Antoine Pitroub530e142010-08-30 12:41:00 +000060
61 f = open("myfile.txt", "r", encoding="utf-8")
62
63In-memory text streams are also available as :class:`StringIO` objects::
64
65 f = io.StringIO("some initial text data")
66
Eli Benderskyf877a7c2012-07-14 21:22:25 +030067The text stream API is described in detail in the documentation of
Benjamin Peterson6b4fa772010-08-30 13:19:53 +000068:class:`TextIOBase`.
Antoine Pitroub530e142010-08-30 12:41:00 +000069
Antoine Pitroub530e142010-08-30 12:41:00 +000070
71Binary I/O
72^^^^^^^^^^
73
Martin Panter6bb91f32016-05-28 00:41:57 +000074Binary I/O (also called *buffered I/O*) expects
75:term:`bytes-like objects <bytes-like object>` and produces :class:`bytes`
Benjamin Peterson6b4fa772010-08-30 13:19:53 +000076objects. No encoding, decoding, or newline translation is performed. This
77category of streams can be used for all kinds of non-text data, and also when
78manual control over the handling of text data is desired.
Antoine Pitroub530e142010-08-30 12:41:00 +000079
Benjamin Peterson6b4fa772010-08-30 13:19:53 +000080The easiest way to create a binary stream is with :meth:`open()` with ``'b'`` in
81the mode string::
Antoine Pitroub530e142010-08-30 12:41:00 +000082
83 f = open("myfile.jpg", "rb")
84
85In-memory binary streams are also available as :class:`BytesIO` objects::
86
87 f = io.BytesIO(b"some initial binary data: \x00\x01")
88
Benjamin Peterson6b4fa772010-08-30 13:19:53 +000089The binary stream API is described in detail in the docs of
90:class:`BufferedIOBase`.
Antoine Pitroub530e142010-08-30 12:41:00 +000091
92Other library modules may provide additional ways to create text or binary
Benjamin Peterson6b4fa772010-08-30 13:19:53 +000093streams. See :meth:`socket.socket.makefile` for example.
94
Antoine Pitroub530e142010-08-30 12:41:00 +000095
96Raw I/O
97^^^^^^^
98
99Raw I/O (also called *unbuffered I/O*) is generally used as a low-level
100building-block for binary and text streams; it is rarely useful to directly
Benjamin Peterson6b4fa772010-08-30 13:19:53 +0000101manipulate a raw stream from user code. Nevertheless, you can create a raw
102stream by opening a file in binary mode with buffering disabled::
Antoine Pitroub530e142010-08-30 12:41:00 +0000103
104 f = open("myfile.jpg", "rb", buffering=0)
105
Benjamin Peterson6b4fa772010-08-30 13:19:53 +0000106The raw stream API is described in detail in the docs of :class:`RawIOBase`.
Benjamin Petersoncc12e1b2010-02-19 00:58:13 +0000107
Georg Brandl014197c2008-04-09 18:40:51 +0000108
Antoine Pitroub530e142010-08-30 12:41:00 +0000109High-level Module Interface
110---------------------------
Georg Brandl014197c2008-04-09 18:40:51 +0000111
112.. data:: DEFAULT_BUFFER_SIZE
113
114 An int containing the default buffer size used by the module's buffered I/O
Benjamin Peterson6b4fa772010-08-30 13:19:53 +0000115 classes. :func:`open` uses the file's blksize (as obtained by
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000116 :func:`os.stat`) if possible.
Georg Brandl014197c2008-04-09 18:40:51 +0000117
Benjamin Peterson6b4fa772010-08-30 13:19:53 +0000118
Andrew Svetlova60de4f2013-02-17 16:55:58 +0200119.. function:: open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
Georg Brandl014197c2008-04-09 18:40:51 +0000120
Benjamin Peterson6b4fa772010-08-30 13:19:53 +0000121 This is an alias for the builtin :func:`open` function.
Georg Brandl014197c2008-04-09 18:40:51 +0000122
Georg Brandl014197c2008-04-09 18:40:51 +0000123
124.. exception:: BlockingIOError
125
Antoine Pitrouf55011f2011-10-12 18:57:23 +0200126 This is a compatibility alias for the builtin :exc:`BlockingIOError`
127 exception.
Georg Brandl014197c2008-04-09 18:40:51 +0000128
129
130.. exception:: UnsupportedOperation
131
Antoine Pitroua787b652011-10-12 19:02:52 +0200132 An exception inheriting :exc:`OSError` and :exc:`ValueError` that is raised
Georg Brandl014197c2008-04-09 18:40:51 +0000133 when an unsupported operation is called on a stream.
134
135
Antoine Pitroub530e142010-08-30 12:41:00 +0000136In-memory streams
137^^^^^^^^^^^^^^^^^
138
Serhiy Storchakae5ea1ab2016-05-18 13:54:54 +0300139It is also possible to use a :class:`str` or :term:`bytes-like object` as a
Benjamin Peterson6b4fa772010-08-30 13:19:53 +0000140file for both reading and writing. For strings :class:`StringIO` can be used
141like a file opened in text mode. :class:`BytesIO` can be used like a file
142opened in binary mode. Both provide full read-write capabilities with random
143access.
Antoine Pitroub530e142010-08-30 12:41:00 +0000144
145
146.. seealso::
Benjamin Peterson6b4fa772010-08-30 13:19:53 +0000147
Antoine Pitroub530e142010-08-30 12:41:00 +0000148 :mod:`sys`
149 contains the standard IO streams: :data:`sys.stdin`, :data:`sys.stdout`,
150 and :data:`sys.stderr`.
151
152
153Class hierarchy
154---------------
155
Benjamin Peterson6b4fa772010-08-30 13:19:53 +0000156The implementation of I/O streams is organized as a hierarchy of classes. First
157:term:`abstract base classes <abstract base class>` (ABCs), which are used to
158specify the various categories of streams, then concrete classes providing the
159standard stream implementations.
Antoine Pitroub530e142010-08-30 12:41:00 +0000160
161 .. note::
Benjamin Peterson6b4fa772010-08-30 13:19:53 +0000162
163 The abstract base classes also provide default implementations of some
164 methods in order to help implementation of concrete stream classes. For
165 example, :class:`BufferedIOBase` provides unoptimized implementations of
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300166 :meth:`~IOBase.readinto` and :meth:`~IOBase.readline`.
Antoine Pitroub530e142010-08-30 12:41:00 +0000167
168At the top of the I/O hierarchy is the abstract base class :class:`IOBase`. It
169defines the basic interface to a stream. Note, however, that there is no
170separation between reading and writing to streams; implementations are allowed
Benjamin Peterson6b4fa772010-08-30 13:19:53 +0000171to raise :exc:`UnsupportedOperation` if they do not support a given operation.
Antoine Pitroub530e142010-08-30 12:41:00 +0000172
Benjamin Peterson6b4fa772010-08-30 13:19:53 +0000173The :class:`RawIOBase` ABC extends :class:`IOBase`. It deals with the reading
174and writing of bytes to a stream. :class:`FileIO` subclasses :class:`RawIOBase`
175to provide an interface to files in the machine's file system.
Antoine Pitroub530e142010-08-30 12:41:00 +0000176
177The :class:`BufferedIOBase` ABC deals with buffering on a raw byte stream
178(:class:`RawIOBase`). Its subclasses, :class:`BufferedWriter`,
179:class:`BufferedReader`, and :class:`BufferedRWPair` buffer streams that are
Benjamin Peterson6b4fa772010-08-30 13:19:53 +0000180readable, writable, and both readable and writable. :class:`BufferedRandom`
181provides a buffered interface to random access streams. Another
Georg Brandl682d7e02010-10-06 10:26:05 +0000182:class:`BufferedIOBase` subclass, :class:`BytesIO`, is a stream of in-memory
Benjamin Peterson6b4fa772010-08-30 13:19:53 +0000183bytes.
Antoine Pitroub530e142010-08-30 12:41:00 +0000184
Benjamin Peterson6b4fa772010-08-30 13:19:53 +0000185The :class:`TextIOBase` ABC, another subclass of :class:`IOBase`, deals with
186streams whose bytes represent text, and handles encoding and decoding to and
187from strings. :class:`TextIOWrapper`, which extends it, is a buffered text
188interface to a buffered raw stream (:class:`BufferedIOBase`). Finally,
189:class:`StringIO` is an in-memory stream for text.
Antoine Pitroub530e142010-08-30 12:41:00 +0000190
191Argument names are not part of the specification, and only the arguments of
Benjamin Peterson6b4fa772010-08-30 13:19:53 +0000192:func:`open` are intended to be used as keyword arguments.
Antoine Pitroub530e142010-08-30 12:41:00 +0000193
Andrew Svetloved636a82012-12-06 12:20:56 +0200194The following table summarizes the ABCs provided by the :mod:`io` module:
195
Georg Brandl44ea77b2013-03-28 13:28:44 +0100196.. tabularcolumns:: |l|l|L|L|
197
Andrew Svetloved636a82012-12-06 12:20:56 +0200198========================= ================== ======================== ==================================================
199ABC Inherits Stub Methods Mixin Methods and Properties
200========================= ================== ======================== ==================================================
201:class:`IOBase` ``fileno``, ``seek``, ``close``, ``closed``, ``__enter__``,
202 and ``truncate`` ``__exit__``, ``flush``, ``isatty``, ``__iter__``,
203 ``__next__``, ``readable``, ``readline``,
204 ``readlines``, ``seekable``, ``tell``,
205 ``writable``, and ``writelines``
206:class:`RawIOBase` :class:`IOBase` ``readinto`` and Inherited :class:`IOBase` methods, ``read``,
207 ``write`` and ``readall``
208:class:`BufferedIOBase` :class:`IOBase` ``detach``, ``read``, Inherited :class:`IOBase` methods, ``readinto``
209 ``read1``, and ``write``
210:class:`TextIOBase` :class:`IOBase` ``detach``, ``read``, Inherited :class:`IOBase` methods, ``encoding``,
211 ``readline``, and ``errors``, and ``newlines``
212 ``write``
213========================= ================== ======================== ==================================================
214
Antoine Pitroub530e142010-08-30 12:41:00 +0000215
Georg Brandl014197c2008-04-09 18:40:51 +0000216I/O Base Classes
Antoine Pitroub530e142010-08-30 12:41:00 +0000217^^^^^^^^^^^^^^^^
Georg Brandl014197c2008-04-09 18:40:51 +0000218
219.. class:: IOBase
220
221 The abstract base class for all I/O classes, acting on streams of bytes.
222 There is no public constructor.
223
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000224 This class provides empty abstract implementations for many methods
225 that derived classes can override selectively; the default
226 implementations represent a file that cannot be read, written or
227 seeked.
Georg Brandl014197c2008-04-09 18:40:51 +0000228
229 Even though :class:`IOBase` does not declare :meth:`read`, :meth:`readinto`,
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000230 or :meth:`write` because their signatures will vary, implementations and
231 clients should consider those methods part of the interface. Also,
Antoine Pitroua787b652011-10-12 19:02:52 +0200232 implementations may raise a :exc:`ValueError` (or :exc:`UnsupportedOperation`)
233 when operations they do not support are called.
Georg Brandl014197c2008-04-09 18:40:51 +0000234
235 The basic type used for binary data read from or written to a file is
Martin Panter6bb91f32016-05-28 00:41:57 +0000236 :class:`bytes`. Other :term:`bytes-like objects <bytes-like object>` are
237 accepted as method arguments too. In some cases, such as
238 :meth:`~RawIOBase.readinto`, a writable object such as :class:`bytearray`
239 is required. Text I/O classes work with :class:`str` data.
Georg Brandl014197c2008-04-09 18:40:51 +0000240
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000241 Note that calling any method (even inquiries) on a closed stream is
Antoine Pitroua787b652011-10-12 19:02:52 +0200242 undefined. Implementations may raise :exc:`ValueError` in this case.
Georg Brandl014197c2008-04-09 18:40:51 +0000243
Éric Araujo3f7c0e42012-12-08 22:53:43 -0500244 :class:`IOBase` (and its subclasses) supports the iterator protocol, meaning
Eli Benderskyf877a7c2012-07-14 21:22:25 +0300245 that an :class:`IOBase` object can be iterated over yielding the lines in a
246 stream. Lines are defined slightly differently depending on whether the
247 stream is a binary stream (yielding bytes), or a text stream (yielding
248 character strings). See :meth:`~IOBase.readline` below.
Georg Brandl014197c2008-04-09 18:40:51 +0000249
Eli Benderskyf877a7c2012-07-14 21:22:25 +0300250 :class:`IOBase` is also a context manager and therefore supports the
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000251 :keyword:`with` statement. In this example, *file* is closed after the
252 :keyword:`with` statement's suite is finished---even if an exception occurs::
Georg Brandl014197c2008-04-09 18:40:51 +0000253
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000254 with open('spam.txt', 'w') as file:
255 file.write('Spam and eggs!')
Georg Brandl014197c2008-04-09 18:40:51 +0000256
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000257 :class:`IOBase` provides these data attributes and methods:
Georg Brandl014197c2008-04-09 18:40:51 +0000258
259 .. method:: close()
260
Christian Heimesecc42a22008-11-05 19:30:32 +0000261 Flush and close this stream. This method has no effect if the file is
Georg Brandl48310cd2009-01-03 21:18:54 +0000262 already closed. Once the file is closed, any operation on the file
Georg Brandl8569e582010-05-19 20:57:08 +0000263 (e.g. reading or writing) will raise a :exc:`ValueError`.
Antoine Pitrouf9fc08f2010-04-28 19:59:32 +0000264
265 As a convenience, it is allowed to call this method more than once;
266 only the first call, however, will have an effect.
Georg Brandl014197c2008-04-09 18:40:51 +0000267
268 .. attribute:: closed
269
Eli Benderskyf877a7c2012-07-14 21:22:25 +0300270 ``True`` if the stream is closed.
Georg Brandl014197c2008-04-09 18:40:51 +0000271
272 .. method:: fileno()
273
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000274 Return the underlying file descriptor (an integer) of the stream if it
Antoine Pitroua787b652011-10-12 19:02:52 +0200275 exists. An :exc:`OSError` is raised if the IO object does not use a file
Georg Brandl014197c2008-04-09 18:40:51 +0000276 descriptor.
277
278 .. method:: flush()
279
Benjamin Petersonb85a5842008-04-13 21:39:58 +0000280 Flush the write buffers of the stream if applicable. This does nothing
281 for read-only and non-blocking streams.
Georg Brandl014197c2008-04-09 18:40:51 +0000282
283 .. method:: isatty()
284
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000285 Return ``True`` if the stream is interactive (i.e., connected to
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000286 a terminal/tty device).
Georg Brandl014197c2008-04-09 18:40:51 +0000287
288 .. method:: readable()
289
Serhiy Storchakafbc1c262013-11-29 12:17:13 +0200290 Return ``True`` if the stream can be read from. If ``False``, :meth:`read`
Antoine Pitroua787b652011-10-12 19:02:52 +0200291 will raise :exc:`OSError`.
Georg Brandl014197c2008-04-09 18:40:51 +0000292
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300293 .. method:: readline(size=-1)
Georg Brandl014197c2008-04-09 18:40:51 +0000294
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300295 Read and return one line from the stream. If *size* is specified, at
296 most *size* bytes will be read.
Georg Brandl014197c2008-04-09 18:40:51 +0000297
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000298 The line terminator is always ``b'\n'`` for binary files; for text files,
Zachary Ware0069eac2014-07-18 09:11:48 -0500299 the *newline* argument to :func:`open` can be used to select the line
Georg Brandl014197c2008-04-09 18:40:51 +0000300 terminator(s) recognized.
301
Georg Brandl3dd33882009-06-01 17:35:27 +0000302 .. method:: readlines(hint=-1)
Georg Brandl014197c2008-04-09 18:40:51 +0000303
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000304 Read and return a list of lines from the stream. *hint* can be specified
305 to control the number of lines read: no more lines will be read if the
306 total size (in bytes/characters) of all lines so far exceeds *hint*.
Georg Brandl014197c2008-04-09 18:40:51 +0000307
Ezio Melottied3cd7e2013-04-15 19:08:31 +0300308 Note that it's already possible to iterate on file objects using ``for
309 line in file: ...`` without calling ``file.readlines()``.
310
Martin Panterdb4220e2015-09-11 03:58:30 +0000311 .. method:: seek(offset[, whence])
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000312
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000313 Change the stream position to the given byte *offset*. *offset* is
Martin Panterdb4220e2015-09-11 03:58:30 +0000314 interpreted relative to the position indicated by *whence*. The default
315 value for *whence* is :data:`SEEK_SET`. Values for *whence* are:
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000316
Benjamin Peterson0e4caf42009-04-01 21:22:20 +0000317 * :data:`SEEK_SET` or ``0`` -- start of the stream (the default);
318 *offset* should be zero or positive
319 * :data:`SEEK_CUR` or ``1`` -- current stream position; *offset* may
320 be negative
321 * :data:`SEEK_END` or ``2`` -- end of the stream; *offset* is usually
322 negative
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000323
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000324 Return the new absolute position.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000325
Raymond Hettinger35a88362009-04-09 00:08:24 +0000326 .. versionadded:: 3.1
Georg Brandl67b21b72010-08-17 15:07:14 +0000327 The ``SEEK_*`` constants.
Benjamin Peterson0e4caf42009-04-01 21:22:20 +0000328
Jesus Cea94363612012-06-22 18:32:07 +0200329 .. versionadded:: 3.3
330 Some operating systems could support additional values, like
331 :data:`os.SEEK_HOLE` or :data:`os.SEEK_DATA`. The valid values
332 for a file could depend on it being open in text or binary mode.
333
Georg Brandl014197c2008-04-09 18:40:51 +0000334 .. method:: seekable()
335
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000336 Return ``True`` if the stream supports random access. If ``False``,
Antoine Pitroua787b652011-10-12 19:02:52 +0200337 :meth:`seek`, :meth:`tell` and :meth:`truncate` will raise :exc:`OSError`.
Georg Brandl014197c2008-04-09 18:40:51 +0000338
339 .. method:: tell()
340
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000341 Return the current stream position.
Georg Brandl014197c2008-04-09 18:40:51 +0000342
Georg Brandl3dd33882009-06-01 17:35:27 +0000343 .. method:: truncate(size=None)
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000344
Antoine Pitrou2016dc92010-05-29 12:08:25 +0000345 Resize the stream to the given *size* in bytes (or the current position
346 if *size* is not specified). The current stream position isn't changed.
347 This resizing can extend or reduce the current file size. In case of
348 extension, the contents of the new file area depend on the platform
Steve Dowerfe0a41a2015-03-20 19:50:46 -0700349 (on most systems, additional bytes are zero-filled). The new file size
350 is returned.
351
352 .. versionchanged:: 3.5
353 Windows will now zero-fill files when extending.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000354
Georg Brandl014197c2008-04-09 18:40:51 +0000355 .. method:: writable()
356
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000357 Return ``True`` if the stream supports writing. If ``False``,
Antoine Pitroua787b652011-10-12 19:02:52 +0200358 :meth:`write` and :meth:`truncate` will raise :exc:`OSError`.
Georg Brandl014197c2008-04-09 18:40:51 +0000359
360 .. method:: writelines(lines)
361
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000362 Write a list of lines to the stream. Line separators are not added, so it
363 is usual for each of the lines provided to have a line separator at the
364 end.
Georg Brandl014197c2008-04-09 18:40:51 +0000365
Benjamin Petersonef8abfc2014-06-14 18:51:34 -0700366 .. method:: __del__()
367
368 Prepare for object destruction. :class:`IOBase` provides a default
369 implementation of this method that calls the instance's
370 :meth:`~IOBase.close` method.
371
Georg Brandl014197c2008-04-09 18:40:51 +0000372
373.. class:: RawIOBase
374
375 Base class for raw binary I/O. It inherits :class:`IOBase`. There is no
376 public constructor.
377
Antoine Pitrou497a7672009-09-17 17:18:01 +0000378 Raw binary I/O typically provides low-level access to an underlying OS
379 device or API, and does not try to encapsulate it in high-level primitives
380 (this is left to Buffered I/O and Text I/O, described later in this page).
381
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000382 In addition to the attributes and methods from :class:`IOBase`,
Eli Benderskyf877a7c2012-07-14 21:22:25 +0300383 :class:`RawIOBase` provides the following methods:
Georg Brandl014197c2008-04-09 18:40:51 +0000384
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300385 .. method:: read(size=-1)
Georg Brandl014197c2008-04-09 18:40:51 +0000386
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300387 Read up to *size* bytes from the object and return them. As a convenience,
388 if *size* is unspecified or -1, :meth:`readall` is called. Otherwise,
389 only one system call is ever made. Fewer than *size* bytes may be
390 returned if the operating system call returns fewer than *size* bytes.
Antoine Pitrou78ddbe62009-10-01 16:24:45 +0000391
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300392 If 0 bytes are returned, and *size* was not 0, this indicates end of file.
Antoine Pitrou78ddbe62009-10-01 16:24:45 +0000393 If the object is in non-blocking mode and no bytes are available,
394 ``None`` is returned.
Georg Brandl014197c2008-04-09 18:40:51 +0000395
Benjamin Petersonb47aace2008-04-09 21:38:38 +0000396 .. method:: readall()
Georg Brandl014197c2008-04-09 18:40:51 +0000397
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000398 Read and return all the bytes from the stream until EOF, using multiple
399 calls to the stream if necessary.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000400
401 .. method:: readinto(b)
402
Martin Panter6bb91f32016-05-28 00:41:57 +0000403 Read bytes into a pre-allocated, writable
404 :term:`bytes-like object` *b*, and return the
Benjamin Peterson2a1a4902014-06-22 14:19:07 -0700405 number of bytes read. If the object is in non-blocking mode and no bytes
406 are available, ``None`` is returned.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000407
408 .. method:: write(b)
409
Martin Panter6bb91f32016-05-28 00:41:57 +0000410 Write the given :term:`bytes-like object`, *b*, to the
411 underlying raw stream, and return the number of
412 bytes written. This can be less than the length of *b* in
413 bytes, depending on specifics of the underlying raw
Eli Benderskyf877a7c2012-07-14 21:22:25 +0300414 stream, and especially if it is in non-blocking mode. ``None`` is
415 returned if the raw stream is set not to block and no single byte could
Martin Panter6bb91f32016-05-28 00:41:57 +0000416 be readily written to it. The caller may release or mutate *b* after
417 this method returns, so the implementation should only access *b*
418 during the method call.
Georg Brandl014197c2008-04-09 18:40:51 +0000419
420
Georg Brandl014197c2008-04-09 18:40:51 +0000421.. class:: BufferedIOBase
422
Antoine Pitrou497a7672009-09-17 17:18:01 +0000423 Base class for binary streams that support some kind of buffering.
424 It inherits :class:`IOBase`. There is no public constructor.
Georg Brandl014197c2008-04-09 18:40:51 +0000425
Antoine Pitrou497a7672009-09-17 17:18:01 +0000426 The main difference with :class:`RawIOBase` is that methods :meth:`read`,
427 :meth:`readinto` and :meth:`write` will try (respectively) to read as much
428 input as requested or to consume all given output, at the expense of
429 making perhaps more than one system call.
430
431 In addition, those methods can raise :exc:`BlockingIOError` if the
432 underlying raw stream is in non-blocking mode and cannot take or give
433 enough data; unlike their :class:`RawIOBase` counterparts, they will
434 never return ``None``.
435
436 Besides, the :meth:`read` method does not have a default
Georg Brandl014197c2008-04-09 18:40:51 +0000437 implementation that defers to :meth:`readinto`.
438
Antoine Pitrou497a7672009-09-17 17:18:01 +0000439 A typical :class:`BufferedIOBase` implementation should not inherit from a
440 :class:`RawIOBase` implementation, but wrap one, like
441 :class:`BufferedWriter` and :class:`BufferedReader` do.
Georg Brandl014197c2008-04-09 18:40:51 +0000442
Senthil Kumarana6bac952011-07-04 11:28:30 -0700443 :class:`BufferedIOBase` provides or overrides these methods and attribute in
444 addition to those from :class:`IOBase`:
Georg Brandl014197c2008-04-09 18:40:51 +0000445
Benjamin Petersonc609b6b2009-06-28 17:32:20 +0000446 .. attribute:: raw
447
448 The underlying raw stream (a :class:`RawIOBase` instance) that
449 :class:`BufferedIOBase` deals with. This is not part of the
450 :class:`BufferedIOBase` API and may not exist on some implementations.
451
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000452 .. method:: detach()
453
454 Separate the underlying raw stream from the buffer and return it.
455
456 After the raw stream has been detached, the buffer is in an unusable
457 state.
458
459 Some buffers, like :class:`BytesIO`, do not have the concept of a single
460 raw stream to return from this method. They raise
461 :exc:`UnsupportedOperation`.
462
Benjamin Petersonedc36472009-05-01 20:48:14 +0000463 .. versionadded:: 3.1
464
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300465 .. method:: read(size=-1)
Georg Brandl014197c2008-04-09 18:40:51 +0000466
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300467 Read and return up to *size* bytes. If the argument is omitted, ``None``,
468 or negative, data is read and returned until EOF is reached. An empty
Eli Benderskyf877a7c2012-07-14 21:22:25 +0300469 :class:`bytes` object is returned if the stream is already at EOF.
Georg Brandl014197c2008-04-09 18:40:51 +0000470
471 If the argument is positive, and the underlying raw stream is not
472 interactive, multiple raw reads may be issued to satisfy the byte count
473 (unless EOF is reached first). But for interactive raw streams, at most
474 one raw read will be issued, and a short result does not imply that EOF is
475 imminent.
476
Antoine Pitrou497a7672009-09-17 17:18:01 +0000477 A :exc:`BlockingIOError` is raised if the underlying raw stream is in
478 non blocking-mode, and has no data available at the moment.
Georg Brandl014197c2008-04-09 18:40:51 +0000479
Martin Panterccb2c0e2016-10-20 23:48:14 +0000480 .. method:: read1([size])
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000481
Benjamin Petersona96fea02014-06-22 14:17:44 -0700482 Read and return up to *size* bytes, with at most one call to the
483 underlying raw stream's :meth:`~RawIOBase.read` (or
Benjamin Peterson2a1a4902014-06-22 14:19:07 -0700484 :meth:`~RawIOBase.readinto`) method. This can be useful if you are
485 implementing your own buffering on top of a :class:`BufferedIOBase`
486 object.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000487
Martin Panter4e946792016-10-21 23:00:10 +0000488 If *size* is ``-1`` (the default), an arbitrary number of bytes are
Martin Panterccb2c0e2016-10-20 23:48:14 +0000489 returned (more than zero unless EOF is reached).
490
Georg Brandl014197c2008-04-09 18:40:51 +0000491 .. method:: readinto(b)
492
Martin Panter6bb91f32016-05-28 00:41:57 +0000493 Read bytes into a pre-allocated, writable
494 :term:`bytes-like object` *b* and return the number of bytes read.
Georg Brandl014197c2008-04-09 18:40:51 +0000495
496 Like :meth:`read`, multiple reads may be issued to the underlying raw
Eli Benderskyf877a7c2012-07-14 21:22:25 +0300497 stream, unless the latter is interactive.
Georg Brandl014197c2008-04-09 18:40:51 +0000498
Benjamin Peterson2a1a4902014-06-22 14:19:07 -0700499 A :exc:`BlockingIOError` is raised if the underlying raw stream is in non
500 blocking-mode, and has no data available at the moment.
Georg Brandl014197c2008-04-09 18:40:51 +0000501
Benjamin Petersona96fea02014-06-22 14:17:44 -0700502 .. method:: readinto1(b)
503
Martin Panter6bb91f32016-05-28 00:41:57 +0000504 Read bytes into a pre-allocated, writable
505 :term:`bytes-like object` *b*, using at most one call to
Benjamin Peterson2a1a4902014-06-22 14:19:07 -0700506 the underlying raw stream's :meth:`~RawIOBase.read` (or
507 :meth:`~RawIOBase.readinto`) method. Return the number of bytes read.
Benjamin Petersona96fea02014-06-22 14:17:44 -0700508
Benjamin Peterson2a1a4902014-06-22 14:19:07 -0700509 A :exc:`BlockingIOError` is raised if the underlying raw stream is in non
510 blocking-mode, and has no data available at the moment.
Benjamin Petersona96fea02014-06-22 14:17:44 -0700511
512 .. versionadded:: 3.5
513
Georg Brandl014197c2008-04-09 18:40:51 +0000514 .. method:: write(b)
515
Martin Panter6bb91f32016-05-28 00:41:57 +0000516 Write the given :term:`bytes-like object`, *b*, and return the number
517 of bytes written (always equal to the length of *b* in bytes, since if
Eli Benderskyf877a7c2012-07-14 21:22:25 +0300518 the write fails an :exc:`OSError` will be raised). Depending on the
519 actual implementation, these bytes may be readily written to the
520 underlying stream, or held in a buffer for performance and latency
521 reasons.
Georg Brandl014197c2008-04-09 18:40:51 +0000522
Antoine Pitrou497a7672009-09-17 17:18:01 +0000523 When in non-blocking mode, a :exc:`BlockingIOError` is raised if the
524 data needed to be written to the raw stream but it couldn't accept
525 all the data without blocking.
Georg Brandl014197c2008-04-09 18:40:51 +0000526
Martin Panter6bb91f32016-05-28 00:41:57 +0000527 The caller may release or mutate *b* after this method returns,
528 so the implementation should only access *b* during the method call.
529
Georg Brandl014197c2008-04-09 18:40:51 +0000530
Benjamin Petersonaa069002009-01-23 03:26:36 +0000531Raw File I/O
Antoine Pitroub530e142010-08-30 12:41:00 +0000532^^^^^^^^^^^^
Benjamin Petersonaa069002009-01-23 03:26:36 +0000533
Ross Lagerwall59142db2011-10-31 20:34:46 +0200534.. class:: FileIO(name, mode='r', closefd=True, opener=None)
Benjamin Petersonaa069002009-01-23 03:26:36 +0000535
Antoine Pitrou497a7672009-09-17 17:18:01 +0000536 :class:`FileIO` represents an OS-level file containing bytes data.
537 It implements the :class:`RawIOBase` interface (and therefore the
538 :class:`IOBase` interface, too).
539
540 The *name* can be one of two things:
541
Eli Benderskyf877a7c2012-07-14 21:22:25 +0300542 * a character string or :class:`bytes` object representing the path to the
Serhiy Storchaka4adf01c2016-10-19 18:30:05 +0300543 file which will be opened. In this case closefd must be ``True`` (the default)
Robert Collins933430a2014-10-18 13:32:43 +1300544 otherwise an error will be raised.
Antoine Pitrou497a7672009-09-17 17:18:01 +0000545 * an integer representing the number of an existing OS-level file descriptor
Robert Collins933430a2014-10-18 13:32:43 +1300546 to which the resulting :class:`FileIO` object will give access. When the
547 FileIO object is closed this fd will be closed as well, unless *closefd*
548 is set to ``False``.
Benjamin Petersonaa069002009-01-23 03:26:36 +0000549
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100550 The *mode* can be ``'r'``, ``'w'``, ``'x'`` or ``'a'`` for reading
Charles-François Natalid612de12012-01-14 11:51:00 +0100551 (default), writing, exclusive creation or appending. The file will be
552 created if it doesn't exist when opened for writing or appending; it will be
553 truncated when opened for writing. :exc:`FileExistsError` will be raised if
554 it already exists when opened for creating. Opening a file for creating
555 implies writing, so this mode behaves in a similar way to ``'w'``. Add a
556 ``'+'`` to the mode to allow simultaneous reading and writing.
Benjamin Petersonaa069002009-01-23 03:26:36 +0000557
Antoine Pitrou497a7672009-09-17 17:18:01 +0000558 The :meth:`read` (when called with a positive argument), :meth:`readinto`
559 and :meth:`write` methods on this class will only make one system call.
560
Ross Lagerwall59142db2011-10-31 20:34:46 +0200561 A custom opener can be used by passing a callable as *opener*. The underlying
562 file descriptor for the file object is then obtained by calling *opener* with
563 (*name*, *flags*). *opener* must return an open file descriptor (passing
564 :mod:`os.open` as *opener* results in functionality similar to passing
565 ``None``).
566
Victor Stinnerdaf45552013-08-28 00:53:59 +0200567 The newly created file is :ref:`non-inheritable <fd_inheritance>`.
568
Éric Araujo8f423c92012-11-03 17:06:52 -0400569 See the :func:`open` built-in function for examples on using the *opener*
570 parameter.
571
Ross Lagerwall59142db2011-10-31 20:34:46 +0200572 .. versionchanged:: 3.3
573 The *opener* parameter was added.
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100574 The ``'x'`` mode was added.
Ross Lagerwall59142db2011-10-31 20:34:46 +0200575
Victor Stinnerdaf45552013-08-28 00:53:59 +0200576 .. versionchanged:: 3.4
577 The file is now non-inheritable.
578
Benjamin Petersonaa069002009-01-23 03:26:36 +0000579 In addition to the attributes and methods from :class:`IOBase` and
580 :class:`RawIOBase`, :class:`FileIO` provides the following data
Eli Benderskyf877a7c2012-07-14 21:22:25 +0300581 attributes:
Benjamin Petersonaa069002009-01-23 03:26:36 +0000582
583 .. attribute:: mode
584
585 The mode as given in the constructor.
586
587 .. attribute:: name
588
589 The file name. This is the file descriptor of the file when no name is
590 given in the constructor.
591
Benjamin Petersonaa069002009-01-23 03:26:36 +0000592
593Buffered Streams
Antoine Pitroub530e142010-08-30 12:41:00 +0000594^^^^^^^^^^^^^^^^
Benjamin Petersonaa069002009-01-23 03:26:36 +0000595
Antoine Pitroubed81c82010-12-03 19:14:17 +0000596Buffered I/O streams provide a higher-level interface to an I/O device
597than raw I/O does.
Antoine Pitrou497a7672009-09-17 17:18:01 +0000598
Georg Brandl014197c2008-04-09 18:40:51 +0000599.. class:: BytesIO([initial_bytes])
600
601 A stream implementation using an in-memory bytes buffer. It inherits
Serhiy Storchakac057c382015-02-03 02:00:18 +0200602 :class:`BufferedIOBase`. The buffer is discarded when the
603 :meth:`~IOBase.close` method is called.
Georg Brandl014197c2008-04-09 18:40:51 +0000604
Martin Panter6bb91f32016-05-28 00:41:57 +0000605 The optional argument *initial_bytes* is a :term:`bytes-like object` that
606 contains initial data.
Georg Brandl014197c2008-04-09 18:40:51 +0000607
608 :class:`BytesIO` provides or overrides these methods in addition to those
609 from :class:`BufferedIOBase` and :class:`IOBase`:
610
Antoine Pitrou972ee132010-09-06 18:48:21 +0000611 .. method:: getbuffer()
612
613 Return a readable and writable view over the contents of the buffer
614 without copying them. Also, mutating the view will transparently
615 update the contents of the buffer::
616
617 >>> b = io.BytesIO(b"abcdef")
618 >>> view = b.getbuffer()
619 >>> view[2:4] = b"56"
620 >>> b.getvalue()
621 b'ab56ef'
622
623 .. note::
624 As long as the view exists, the :class:`BytesIO` object cannot be
Serhiy Storchakac057c382015-02-03 02:00:18 +0200625 resized or closed.
Antoine Pitrou972ee132010-09-06 18:48:21 +0000626
627 .. versionadded:: 3.2
628
Georg Brandl014197c2008-04-09 18:40:51 +0000629 .. method:: getvalue()
630
Eli Benderskyf877a7c2012-07-14 21:22:25 +0300631 Return :class:`bytes` containing the entire contents of the buffer.
Georg Brandl014197c2008-04-09 18:40:51 +0000632
Serhiy Storchakac057c382015-02-03 02:00:18 +0200633
Martin Panterccb2c0e2016-10-20 23:48:14 +0000634 .. method:: read1([size])
Georg Brandl014197c2008-04-09 18:40:51 +0000635
Martin Panterccb2c0e2016-10-20 23:48:14 +0000636 In :class:`BytesIO`, this is the same as :meth:`~BufferedIOBase.read`.
Georg Brandl014197c2008-04-09 18:40:51 +0000637
Martin Panterccb2c0e2016-10-20 23:48:14 +0000638 .. versionchanged:: 3.7
639 The *size* argument is now optional.
Benjamin Petersona96fea02014-06-22 14:17:44 -0700640
Martin Panterccb2c0e2016-10-20 23:48:14 +0000641 .. method:: readinto1(b)
642
643 In :class:`BytesIO`, this is the same as :meth:`~BufferedIOBase.readinto`.
Benjamin Petersona96fea02014-06-22 14:17:44 -0700644
645 .. versionadded:: 3.5
Georg Brandl014197c2008-04-09 18:40:51 +0000646
Georg Brandl3dd33882009-06-01 17:35:27 +0000647.. class:: BufferedReader(raw, buffer_size=DEFAULT_BUFFER_SIZE)
Georg Brandl014197c2008-04-09 18:40:51 +0000648
Antoine Pitrou497a7672009-09-17 17:18:01 +0000649 A buffer providing higher-level access to a readable, sequential
650 :class:`RawIOBase` object. It inherits :class:`BufferedIOBase`.
651 When reading data from this object, a larger amount of data may be
652 requested from the underlying raw stream, and kept in an internal buffer.
653 The buffered data can then be returned directly on subsequent reads.
Georg Brandl014197c2008-04-09 18:40:51 +0000654
655 The constructor creates a :class:`BufferedReader` for the given readable
656 *raw* stream and *buffer_size*. If *buffer_size* is omitted,
657 :data:`DEFAULT_BUFFER_SIZE` is used.
658
659 :class:`BufferedReader` provides or overrides these methods in addition to
660 those from :class:`BufferedIOBase` and :class:`IOBase`:
661
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300662 .. method:: peek([size])
Georg Brandl014197c2008-04-09 18:40:51 +0000663
Benjamin Petersonc43a26d2009-06-16 23:09:24 +0000664 Return bytes from the stream without advancing the position. At most one
Benjamin Peterson2a8b54d2009-06-14 14:37:23 +0000665 single read on the raw stream is done to satisfy the call. The number of
666 bytes returned may be less or more than requested.
Georg Brandl014197c2008-04-09 18:40:51 +0000667
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300668 .. method:: read([size])
Georg Brandl014197c2008-04-09 18:40:51 +0000669
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300670 Read and return *size* bytes, or if *size* is not given or negative, until
671 EOF or if the read call would block in non-blocking mode.
Georg Brandl014197c2008-04-09 18:40:51 +0000672
Martin Panterccb2c0e2016-10-20 23:48:14 +0000673 .. method:: read1([size])
Georg Brandl014197c2008-04-09 18:40:51 +0000674
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300675 Read and return up to *size* bytes with only one call on the raw stream.
676 If at least one byte is buffered, only buffered bytes are returned.
Georg Brandl014197c2008-04-09 18:40:51 +0000677 Otherwise, one raw stream read call is made.
678
Martin Panterccb2c0e2016-10-20 23:48:14 +0000679 .. versionchanged:: 3.7
680 The *size* argument is now optional.
681
Georg Brandl014197c2008-04-09 18:40:51 +0000682
Georg Brandl3dd33882009-06-01 17:35:27 +0000683.. class:: BufferedWriter(raw, buffer_size=DEFAULT_BUFFER_SIZE)
Georg Brandl014197c2008-04-09 18:40:51 +0000684
Antoine Pitrou497a7672009-09-17 17:18:01 +0000685 A buffer providing higher-level access to a writeable, sequential
686 :class:`RawIOBase` object. It inherits :class:`BufferedIOBase`.
Eli Benderskyf877a7c2012-07-14 21:22:25 +0300687 When writing to this object, data is normally placed into an internal
Antoine Pitrou497a7672009-09-17 17:18:01 +0000688 buffer. The buffer will be written out to the underlying :class:`RawIOBase`
689 object under various conditions, including:
690
691 * when the buffer gets too small for all pending data;
692 * when :meth:`flush()` is called;
693 * when a :meth:`seek()` is requested (for :class:`BufferedRandom` objects);
694 * when the :class:`BufferedWriter` object is closed or destroyed.
Georg Brandl014197c2008-04-09 18:40:51 +0000695
696 The constructor creates a :class:`BufferedWriter` for the given writeable
697 *raw* stream. If the *buffer_size* is not given, it defaults to
Benjamin Peterson394ee002009-03-05 22:33:59 +0000698 :data:`DEFAULT_BUFFER_SIZE`.
699
Georg Brandl014197c2008-04-09 18:40:51 +0000700 :class:`BufferedWriter` provides or overrides these methods in addition to
701 those from :class:`BufferedIOBase` and :class:`IOBase`:
702
703 .. method:: flush()
704
705 Force bytes held in the buffer into the raw stream. A
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000706 :exc:`BlockingIOError` should be raised if the raw stream blocks.
Georg Brandl014197c2008-04-09 18:40:51 +0000707
708 .. method:: write(b)
709
Martin Panter6bb91f32016-05-28 00:41:57 +0000710 Write the :term:`bytes-like object`, *b*, and return the
Eli Benderskyf877a7c2012-07-14 21:22:25 +0300711 number of bytes written. When in non-blocking mode, a
712 :exc:`BlockingIOError` is raised if the buffer needs to be written out but
713 the raw stream blocks.
Georg Brandl014197c2008-04-09 18:40:51 +0000714
715
Georg Brandl3dd33882009-06-01 17:35:27 +0000716.. class:: BufferedRandom(raw, buffer_size=DEFAULT_BUFFER_SIZE)
Georg Brandl014197c2008-04-09 18:40:51 +0000717
718 A buffered interface to random access streams. It inherits
Antoine Pitrou497a7672009-09-17 17:18:01 +0000719 :class:`BufferedReader` and :class:`BufferedWriter`, and further supports
720 :meth:`seek` and :meth:`tell` functionality.
Georg Brandl014197c2008-04-09 18:40:51 +0000721
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000722 The constructor creates a reader and writer for a seekable raw stream, given
Georg Brandl014197c2008-04-09 18:40:51 +0000723 in the first argument. If the *buffer_size* is omitted it defaults to
Benjamin Peterson394ee002009-03-05 22:33:59 +0000724 :data:`DEFAULT_BUFFER_SIZE`.
725
Georg Brandl014197c2008-04-09 18:40:51 +0000726 :class:`BufferedRandom` is capable of anything :class:`BufferedReader` or
727 :class:`BufferedWriter` can do.
728
729
Antoine Pitrou13d28952011-08-20 19:48:43 +0200730.. class:: BufferedRWPair(reader, writer, buffer_size=DEFAULT_BUFFER_SIZE)
731
732 A buffered I/O object combining two unidirectional :class:`RawIOBase`
733 objects -- one readable, the other writeable -- into a single bidirectional
734 endpoint. It inherits :class:`BufferedIOBase`.
735
736 *reader* and *writer* are :class:`RawIOBase` objects that are readable and
737 writeable respectively. If the *buffer_size* is omitted it defaults to
738 :data:`DEFAULT_BUFFER_SIZE`.
739
Antoine Pitrou13d28952011-08-20 19:48:43 +0200740 :class:`BufferedRWPair` implements all of :class:`BufferedIOBase`\'s methods
741 except for :meth:`~BufferedIOBase.detach`, which raises
742 :exc:`UnsupportedOperation`.
743
744 .. warning::
Larry Hastings3732ed22014-03-15 21:13:56 -0700745
Antoine Pitrou13d28952011-08-20 19:48:43 +0200746 :class:`BufferedRWPair` does not attempt to synchronize accesses to
747 its underlying raw streams. You should not pass it the same object
748 as reader and writer; use :class:`BufferedRandom` instead.
749
750
Georg Brandl014197c2008-04-09 18:40:51 +0000751Text I/O
Antoine Pitroub530e142010-08-30 12:41:00 +0000752^^^^^^^^
Georg Brandl014197c2008-04-09 18:40:51 +0000753
754.. class:: TextIOBase
755
756 Base class for text streams. This class provides a character and line based
757 interface to stream I/O. There is no :meth:`readinto` method because
758 Python's character strings are immutable. It inherits :class:`IOBase`.
759 There is no public constructor.
760
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000761 :class:`TextIOBase` provides or overrides these data attributes and
762 methods in addition to those from :class:`IOBase`:
Georg Brandl014197c2008-04-09 18:40:51 +0000763
764 .. attribute:: encoding
765
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000766 The name of the encoding used to decode the stream's bytes into
Georg Brandl014197c2008-04-09 18:40:51 +0000767 strings, and to encode strings into bytes.
768
Benjamin Peterson0926ad12009-06-06 18:02:12 +0000769 .. attribute:: errors
770
771 The error setting of the decoder or encoder.
772
Georg Brandl014197c2008-04-09 18:40:51 +0000773 .. attribute:: newlines
774
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000775 A string, a tuple of strings, or ``None``, indicating the newlines
Antoine Pitrou497a7672009-09-17 17:18:01 +0000776 translated so far. Depending on the implementation and the initial
777 constructor flags, this may not be available.
Georg Brandl014197c2008-04-09 18:40:51 +0000778
Benjamin Petersonc609b6b2009-06-28 17:32:20 +0000779 .. attribute:: buffer
780
781 The underlying binary buffer (a :class:`BufferedIOBase` instance) that
782 :class:`TextIOBase` deals with. This is not part of the
Eli Benderskyf877a7c2012-07-14 21:22:25 +0300783 :class:`TextIOBase` API and may not exist in some implementations.
Benjamin Petersonc609b6b2009-06-28 17:32:20 +0000784
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000785 .. method:: detach()
786
Antoine Pitrou497a7672009-09-17 17:18:01 +0000787 Separate the underlying binary buffer from the :class:`TextIOBase` and
788 return it.
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000789
790 After the underlying buffer has been detached, the :class:`TextIOBase` is
791 in an unusable state.
792
793 Some :class:`TextIOBase` implementations, like :class:`StringIO`, may not
794 have the concept of an underlying buffer and calling this method will
795 raise :exc:`UnsupportedOperation`.
796
Benjamin Petersonedc36472009-05-01 20:48:14 +0000797 .. versionadded:: 3.1
798
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300799 .. method:: read(size)
Georg Brandl014197c2008-04-09 18:40:51 +0000800
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300801 Read and return at most *size* characters from the stream as a single
802 :class:`str`. If *size* is negative or ``None``, reads until EOF.
Georg Brandl014197c2008-04-09 18:40:51 +0000803
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300804 .. method:: readline(size=-1)
Georg Brandl014197c2008-04-09 18:40:51 +0000805
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000806 Read until newline or EOF and return a single ``str``. If the stream is
807 already at EOF, an empty string is returned.
Georg Brandl014197c2008-04-09 18:40:51 +0000808
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300809 If *size* is specified, at most *size* characters will be read.
Antoine Pitrou707bd4e2012-07-25 22:38:33 +0200810
Martin Panterdb4220e2015-09-11 03:58:30 +0000811 .. method:: seek(offset[, whence])
Antoine Pitrouf49d1522012-01-21 20:20:49 +0100812
Martin Panterdb4220e2015-09-11 03:58:30 +0000813 Change the stream position to the given *offset*. Behaviour depends on
814 the *whence* parameter. The default value for *whence* is
815 :data:`SEEK_SET`.
Antoine Pitrouf49d1522012-01-21 20:20:49 +0100816
817 * :data:`SEEK_SET` or ``0``: seek from the start of the stream
818 (the default); *offset* must either be a number returned by
819 :meth:`TextIOBase.tell`, or zero. Any other *offset* value
820 produces undefined behaviour.
821 * :data:`SEEK_CUR` or ``1``: "seek" to the current position;
822 *offset* must be zero, which is a no-operation (all other values
823 are unsupported).
824 * :data:`SEEK_END` or ``2``: seek to the end of the stream;
825 *offset* must be zero (all other values are unsupported).
826
827 Return the new absolute position as an opaque number.
828
829 .. versionadded:: 3.1
830 The ``SEEK_*`` constants.
831
832 .. method:: tell()
833
834 Return the current stream position as an opaque number. The number
835 does not usually represent a number of bytes in the underlying
836 binary storage.
837
Georg Brandl014197c2008-04-09 18:40:51 +0000838 .. method:: write(s)
839
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000840 Write the string *s* to the stream and return the number of characters
841 written.
Georg Brandl014197c2008-04-09 18:40:51 +0000842
843
Antoine Pitrou664091b2011-07-23 22:00:03 +0200844.. class:: TextIOWrapper(buffer, encoding=None, errors=None, newline=None, \
845 line_buffering=False, write_through=False)
Georg Brandl014197c2008-04-09 18:40:51 +0000846
Antoine Pitrou497a7672009-09-17 17:18:01 +0000847 A buffered text stream over a :class:`BufferedIOBase` binary stream.
Georg Brandl014197c2008-04-09 18:40:51 +0000848 It inherits :class:`TextIOBase`.
849
850 *encoding* gives the name of the encoding that the stream will be decoded or
Andrew Svetlov4805fa82012-08-13 22:11:14 +0300851 encoded with. It defaults to
852 :func:`locale.getpreferredencoding(False) <locale.getpreferredencoding>`.
Georg Brandl014197c2008-04-09 18:40:51 +0000853
Benjamin Petersonb85a5842008-04-13 21:39:58 +0000854 *errors* is an optional string that specifies how encoding and decoding
855 errors are to be handled. Pass ``'strict'`` to raise a :exc:`ValueError`
856 exception if there is an encoding error (the default of ``None`` has the same
857 effect), or pass ``'ignore'`` to ignore errors. (Note that ignoring encoding
858 errors can lead to data loss.) ``'replace'`` causes a replacement marker
Serhiy Storchaka07985ef2015-01-25 22:56:57 +0200859 (such as ``'?'``) to be inserted where there is malformed data.
860 ``'backslashreplace'`` causes malformed data to be replaced by a
861 backslashed escape sequence. When writing, ``'xmlcharrefreplace'``
862 (replace with the appropriate XML character reference) or ``'namereplace'``
863 (replace with ``\N{...}`` escape sequences) can be used. Any other error
864 handling name that has been registered with
Serhiy Storchaka166ebc42014-11-25 13:57:17 +0200865 :func:`codecs.register_error` is also valid.
Georg Brandl014197c2008-04-09 18:40:51 +0000866
R David Murray1b00f252012-08-15 10:43:58 -0400867 .. index::
868 single: universal newlines; io.TextIOWrapper class
869
Antoine Pitrou0c1c0d42012-08-04 00:55:38 +0200870 *newline* controls how line endings are handled. It can be ``None``,
871 ``''``, ``'\n'``, ``'\r'``, and ``'\r\n'``. It works as follows:
872
R David Murray1b00f252012-08-15 10:43:58 -0400873 * When reading input from the stream, if *newline* is ``None``,
R David Murrayee0a9452012-08-15 11:05:36 -0400874 :term:`universal newlines` mode is enabled. Lines in the input can end in
875 ``'\n'``, ``'\r'``, or ``'\r\n'``, and these are translated into ``'\n'``
876 before being returned to the caller. If it is ``''``, universal newlines
877 mode is enabled, but line endings are returned to the caller untranslated.
878 If it has any of the other legal values, input lines are only terminated
879 by the given string, and the line ending is returned to the caller
880 untranslated.
Antoine Pitrou0c1c0d42012-08-04 00:55:38 +0200881
Georg Brandl296d1be2012-08-14 09:39:07 +0200882 * When writing output to the stream, if *newline* is ``None``, any ``'\n'``
883 characters written are translated to the system default line separator,
884 :data:`os.linesep`. If *newline* is ``''`` or ``'\n'``, no translation
885 takes place. If *newline* is any of the other legal values, any ``'\n'``
886 characters written are translated to the given string.
Georg Brandl014197c2008-04-09 18:40:51 +0000887
888 If *line_buffering* is ``True``, :meth:`flush` is implied when a call to
889 write contains a newline character.
890
Antoine Pitrou664091b2011-07-23 22:00:03 +0200891 If *write_through* is ``True``, calls to :meth:`write` are guaranteed
892 not to be buffered: any data written on the :class:`TextIOWrapper`
893 object is immediately handled to its underlying binary *buffer*.
894
895 .. versionchanged:: 3.3
896 The *write_through* argument has been added.
897
Victor Stinnerf86a5e82012-06-05 13:43:22 +0200898 .. versionchanged:: 3.3
899 The default *encoding* is now ``locale.getpreferredencoding(False)``
900 instead of ``locale.getpreferredencoding()``. Don't change temporary the
901 locale encoding using :func:`locale.setlocale`, use the current locale
902 encoding instead of the user preferred encoding.
903
Benjamin Peterson0926ad12009-06-06 18:02:12 +0000904 :class:`TextIOWrapper` provides one attribute in addition to those of
Georg Brandl014197c2008-04-09 18:40:51 +0000905 :class:`TextIOBase` and its parents:
906
Georg Brandl014197c2008-04-09 18:40:51 +0000907 .. attribute:: line_buffering
908
909 Whether line buffering is enabled.
Georg Brandl48310cd2009-01-03 21:18:54 +0000910
Georg Brandl014197c2008-04-09 18:40:51 +0000911
Antoine Pitroube7ff9f2014-02-02 22:48:25 +0100912.. class:: StringIO(initial_value='', newline='\\n')
Georg Brandl014197c2008-04-09 18:40:51 +0000913
Serhiy Storchakac057c382015-02-03 02:00:18 +0200914 An in-memory stream for text I/O. The text buffer is discarded when the
915 :meth:`~IOBase.close` method is called.
Georg Brandl014197c2008-04-09 18:40:51 +0000916
Martin Pantercfad5432015-10-10 03:01:20 +0000917 The initial value of the buffer can be set by providing *initial_value*.
918 If newline translation is enabled, newlines will be encoded as if by
919 :meth:`~TextIOBase.write`. The stream is positioned at the start of
920 the buffer.
921
922 The *newline* argument works like that of :class:`TextIOWrapper`.
923 The default is to consider only ``\n`` characters as ends of lines and
924 to do no newline translation. If *newline* is set to ``None``,
925 newlines are written as ``\n`` on all platforms, but universal
926 newline decoding is still performed when reading.
Georg Brandl014197c2008-04-09 18:40:51 +0000927
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000928 :class:`StringIO` provides this method in addition to those from
Antoine Pitroub530e142010-08-30 12:41:00 +0000929 :class:`TextIOBase` and its parents:
Georg Brandl014197c2008-04-09 18:40:51 +0000930
931 .. method:: getvalue()
932
Serhiy Storchakac057c382015-02-03 02:00:18 +0200933 Return a ``str`` containing the entire contents of the buffer.
Martin Pantercfad5432015-10-10 03:01:20 +0000934 Newlines are decoded as if by :meth:`~TextIOBase.read`, although
935 the stream position is not changed.
Georg Brandl014197c2008-04-09 18:40:51 +0000936
Georg Brandl2932d932008-05-30 06:27:09 +0000937 Example usage::
938
939 import io
940
941 output = io.StringIO()
942 output.write('First line.\n')
943 print('Second line.', file=output)
944
945 # Retrieve file contents -- this will be
946 # 'First line.\nSecond line.\n'
947 contents = output.getvalue()
948
Georg Brandl48310cd2009-01-03 21:18:54 +0000949 # Close object and discard memory buffer --
Georg Brandl2932d932008-05-30 06:27:09 +0000950 # .getvalue() will now raise an exception.
951 output.close()
Georg Brandl014197c2008-04-09 18:40:51 +0000952
Antoine Pitroub530e142010-08-30 12:41:00 +0000953
R David Murray1b00f252012-08-15 10:43:58 -0400954.. index::
955 single: universal newlines; io.IncrementalNewlineDecoder class
956
Georg Brandl014197c2008-04-09 18:40:51 +0000957.. class:: IncrementalNewlineDecoder
958
R David Murray1b00f252012-08-15 10:43:58 -0400959 A helper codec that decodes newlines for :term:`universal newlines` mode.
960 It inherits :class:`codecs.IncrementalDecoder`.
Georg Brandl014197c2008-04-09 18:40:51 +0000961
Antoine Pitroubed81c82010-12-03 19:14:17 +0000962
Antoine Pitroubed81c82010-12-03 19:14:17 +0000963Performance
Benjamin Petersonedf51322011-02-24 03:03:46 +0000964-----------
965
966This section discusses the performance of the provided concrete I/O
967implementations.
Antoine Pitroubed81c82010-12-03 19:14:17 +0000968
969Binary I/O
Benjamin Petersonedf51322011-02-24 03:03:46 +0000970^^^^^^^^^^
Antoine Pitroubed81c82010-12-03 19:14:17 +0000971
Benjamin Petersonedf51322011-02-24 03:03:46 +0000972By reading and writing only large chunks of data even when the user asks for a
973single byte, buffered I/O hides any inefficiency in calling and executing the
974operating system's unbuffered I/O routines. The gain depends on the OS and the
975kind of I/O which is performed. For example, on some modern OSes such as Linux,
976unbuffered disk I/O can be as fast as buffered I/O. The bottom line, however,
977is that buffered I/O offers predictable performance regardless of the platform
Eli Benderskyf877a7c2012-07-14 21:22:25 +0300978and the backing device. Therefore, it is almost always preferable to use
979buffered I/O rather than unbuffered I/O for binary data.
Antoine Pitroubed81c82010-12-03 19:14:17 +0000980
981Text I/O
Benjamin Petersonedf51322011-02-24 03:03:46 +0000982^^^^^^^^
Antoine Pitroubed81c82010-12-03 19:14:17 +0000983
984Text I/O over a binary storage (such as a file) is significantly slower than
Benjamin Petersonedf51322011-02-24 03:03:46 +0000985binary I/O over the same storage, because it requires conversions between
986unicode and binary data using a character codec. This can become noticeable
987handling huge amounts of text data like large log files. Also,
988:meth:`TextIOWrapper.tell` and :meth:`TextIOWrapper.seek` are both quite slow
989due to the reconstruction algorithm used.
Antoine Pitroubed81c82010-12-03 19:14:17 +0000990
991:class:`StringIO`, however, is a native in-memory unicode container and will
992exhibit similar speed to :class:`BytesIO`.
993
994Multi-threading
995^^^^^^^^^^^^^^^
996
Benjamin Petersonedf51322011-02-24 03:03:46 +0000997:class:`FileIO` objects are thread-safe to the extent that the operating system
998calls (such as ``read(2)`` under Unix) they wrap are thread-safe too.
Antoine Pitroubed81c82010-12-03 19:14:17 +0000999
1000Binary buffered objects (instances of :class:`BufferedReader`,
1001:class:`BufferedWriter`, :class:`BufferedRandom` and :class:`BufferedRWPair`)
1002protect their internal structures using a lock; it is therefore safe to call
1003them from multiple threads at once.
1004
1005:class:`TextIOWrapper` objects are not thread-safe.
1006
1007Reentrancy
1008^^^^^^^^^^
1009
1010Binary buffered objects (instances of :class:`BufferedReader`,
1011:class:`BufferedWriter`, :class:`BufferedRandom` and :class:`BufferedRWPair`)
1012are not reentrant. While reentrant calls will not happen in normal situations,
Benjamin Petersonedf51322011-02-24 03:03:46 +00001013they can arise from doing I/O in a :mod:`signal` handler. If a thread tries to
Eli Benderskyf877a7c2012-07-14 21:22:25 +03001014re-enter a buffered object which it is already accessing, a :exc:`RuntimeError`
1015is raised. Note this doesn't prohibit a different thread from entering the
Benjamin Petersonedf51322011-02-24 03:03:46 +00001016buffered object.
Antoine Pitroubed81c82010-12-03 19:14:17 +00001017
Benjamin Petersonedf51322011-02-24 03:03:46 +00001018The above implicitly extends to text files, since the :func:`open()` function
1019will wrap a buffered object inside a :class:`TextIOWrapper`. This includes
1020standard streams and therefore affects the built-in function :func:`print()` as
1021well.
Antoine Pitroubed81c82010-12-03 19:14:17 +00001022