blob: 2b55018550c53518bbc92e2997e269dae8580c20 [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.
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>
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00009.. moduleauthor:: Antoine Pitrou <solipsis@pitrou.net>
10.. moduleauthor:: Amaury Forgeot d'Arc <amauryfa@gmail.com>
Benjamin Petersonef9f2bd2009-05-01 20:45:43 +000011.. moduleauthor:: Benjamin Peterson <benjamin@python.org>
Benjamin Peterson058e31e2009-01-16 03:54:08 +000012.. sectionauthor:: Benjamin Peterson <benjamin@python.org>
Georg Brandl014197c2008-04-09 18:40:51 +000013
Benjamin Peterson6b4fa772010-08-30 13:19:53 +000014.. _io-overview:
15
Antoine Pitroub530e142010-08-30 12:41:00 +000016Overview
17--------
Georg Brandl014197c2008-04-09 18:40:51 +000018
R David Murray9f0c9402012-08-17 20:33:54 -040019.. index::
20 single: file object; io module
21
22The :mod:`io` module provides Python's main facilities for dealing with various
23types of I/O. There are three main types of I/O: *text I/O*, *binary I/O*
24and *raw I/O*. These are generic categories, and various backing stores can
25be used for each of them. A concrete object belonging to any of these
26categories is called a :term:`file object`. Other common terms are *stream*
27and *file-like object*.
Georg Brandl014197c2008-04-09 18:40:51 +000028
Antoine Pitroub530e142010-08-30 12:41:00 +000029Independently of its category, each concrete stream object will also have
Benjamin Peterson6b4fa772010-08-30 13:19:53 +000030various capabilities: it can be read-only, write-only, or read-write. It can
31also allow arbitrary random access (seeking forwards or backwards to any
32location), or only sequential access (for example in the case of a socket or
33pipe).
Georg Brandl014197c2008-04-09 18:40:51 +000034
Antoine Pitroub530e142010-08-30 12:41:00 +000035All streams are careful about the type of data you give to them. For example
36giving a :class:`str` object to the ``write()`` method of a binary stream
37will raise a ``TypeError``. So will giving a :class:`bytes` object to the
38``write()`` method of a text stream.
Georg Brandl014197c2008-04-09 18:40:51 +000039
Antoine Pitroua787b652011-10-12 19:02:52 +020040.. versionchanged:: 3.3
Eli Benderskyf877a7c2012-07-14 21:22:25 +030041 Operations that used to raise :exc:`IOError` now raise :exc:`OSError`, since
42 :exc:`IOError` is now an alias of :exc:`OSError`.
Antoine Pitroua787b652011-10-12 19:02:52 +020043
Benjamin Peterson6b4fa772010-08-30 13:19:53 +000044
Antoine Pitroub530e142010-08-30 12:41:00 +000045Text I/O
46^^^^^^^^
Georg Brandl014197c2008-04-09 18:40:51 +000047
Benjamin Peterson6b4fa772010-08-30 13:19:53 +000048Text I/O expects and produces :class:`str` objects. This means that whenever
49the backing store is natively made of bytes (such as in the case of a file),
50encoding and decoding of data is made transparently as well as optional
51translation of platform-specific newline characters.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +000052
Benjamin Peterson6b4fa772010-08-30 13:19:53 +000053The easiest way to create a text stream is with :meth:`open()`, optionally
54specifying an encoding::
Antoine Pitroub530e142010-08-30 12:41:00 +000055
56 f = open("myfile.txt", "r", encoding="utf-8")
57
58In-memory text streams are also available as :class:`StringIO` objects::
59
60 f = io.StringIO("some initial text data")
61
Eli Benderskyf877a7c2012-07-14 21:22:25 +030062The text stream API is described in detail in the documentation of
Benjamin Peterson6b4fa772010-08-30 13:19:53 +000063:class:`TextIOBase`.
Antoine Pitroub530e142010-08-30 12:41:00 +000064
Antoine Pitroub530e142010-08-30 12:41:00 +000065
66Binary I/O
67^^^^^^^^^^
68
Benjamin Peterson6b4fa772010-08-30 13:19:53 +000069Binary I/O (also called *buffered I/O*) expects and produces :class:`bytes`
70objects. No encoding, decoding, or newline translation is performed. This
71category of streams can be used for all kinds of non-text data, and also when
72manual control over the handling of text data is desired.
Antoine Pitroub530e142010-08-30 12:41:00 +000073
Benjamin Peterson6b4fa772010-08-30 13:19:53 +000074The easiest way to create a binary stream is with :meth:`open()` with ``'b'`` in
75the mode string::
Antoine Pitroub530e142010-08-30 12:41:00 +000076
77 f = open("myfile.jpg", "rb")
78
79In-memory binary streams are also available as :class:`BytesIO` objects::
80
81 f = io.BytesIO(b"some initial binary data: \x00\x01")
82
Benjamin Peterson6b4fa772010-08-30 13:19:53 +000083The binary stream API is described in detail in the docs of
84:class:`BufferedIOBase`.
Antoine Pitroub530e142010-08-30 12:41:00 +000085
86Other library modules may provide additional ways to create text or binary
Benjamin Peterson6b4fa772010-08-30 13:19:53 +000087streams. See :meth:`socket.socket.makefile` for example.
88
Antoine Pitroub530e142010-08-30 12:41:00 +000089
90Raw I/O
91^^^^^^^
92
93Raw I/O (also called *unbuffered I/O*) is generally used as a low-level
94building-block for binary and text streams; it is rarely useful to directly
Benjamin Peterson6b4fa772010-08-30 13:19:53 +000095manipulate a raw stream from user code. Nevertheless, you can create a raw
96stream by opening a file in binary mode with buffering disabled::
Antoine Pitroub530e142010-08-30 12:41:00 +000097
98 f = open("myfile.jpg", "rb", buffering=0)
99
Benjamin Peterson6b4fa772010-08-30 13:19:53 +0000100The raw stream API is described in detail in the docs of :class:`RawIOBase`.
Benjamin Petersoncc12e1b2010-02-19 00:58:13 +0000101
Georg Brandl014197c2008-04-09 18:40:51 +0000102
Antoine Pitroub530e142010-08-30 12:41:00 +0000103High-level Module Interface
104---------------------------
Georg Brandl014197c2008-04-09 18:40:51 +0000105
106.. data:: DEFAULT_BUFFER_SIZE
107
108 An int containing the default buffer size used by the module's buffered I/O
Benjamin Peterson6b4fa772010-08-30 13:19:53 +0000109 classes. :func:`open` uses the file's blksize (as obtained by
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000110 :func:`os.stat`) if possible.
Georg Brandl014197c2008-04-09 18:40:51 +0000111
Benjamin Peterson6b4fa772010-08-30 13:19:53 +0000112
Andrew Svetlova60de4f2013-02-17 16:55:58 +0200113.. function:: open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
Georg Brandl014197c2008-04-09 18:40:51 +0000114
Benjamin Peterson6b4fa772010-08-30 13:19:53 +0000115 This is an alias for the builtin :func:`open` function.
Georg Brandl014197c2008-04-09 18:40:51 +0000116
Georg Brandl014197c2008-04-09 18:40:51 +0000117
118.. exception:: BlockingIOError
119
Antoine Pitrouf55011f2011-10-12 18:57:23 +0200120 This is a compatibility alias for the builtin :exc:`BlockingIOError`
121 exception.
Georg Brandl014197c2008-04-09 18:40:51 +0000122
123
124.. exception:: UnsupportedOperation
125
Antoine Pitroua787b652011-10-12 19:02:52 +0200126 An exception inheriting :exc:`OSError` and :exc:`ValueError` that is raised
Georg Brandl014197c2008-04-09 18:40:51 +0000127 when an unsupported operation is called on a stream.
128
129
Antoine Pitroub530e142010-08-30 12:41:00 +0000130In-memory streams
131^^^^^^^^^^^^^^^^^
132
133It is also possible to use a :class:`str` or :class:`bytes`-like object as a
Benjamin Peterson6b4fa772010-08-30 13:19:53 +0000134file for both reading and writing. For strings :class:`StringIO` can be used
135like a file opened in text mode. :class:`BytesIO` can be used like a file
136opened in binary mode. Both provide full read-write capabilities with random
137access.
Antoine Pitroub530e142010-08-30 12:41:00 +0000138
139
140.. seealso::
Benjamin Peterson6b4fa772010-08-30 13:19:53 +0000141
Antoine Pitroub530e142010-08-30 12:41:00 +0000142 :mod:`sys`
143 contains the standard IO streams: :data:`sys.stdin`, :data:`sys.stdout`,
144 and :data:`sys.stderr`.
145
146
147Class hierarchy
148---------------
149
Benjamin Peterson6b4fa772010-08-30 13:19:53 +0000150The implementation of I/O streams is organized as a hierarchy of classes. First
151:term:`abstract base classes <abstract base class>` (ABCs), which are used to
152specify the various categories of streams, then concrete classes providing the
153standard stream implementations.
Antoine Pitroub530e142010-08-30 12:41:00 +0000154
155 .. note::
Benjamin Peterson6b4fa772010-08-30 13:19:53 +0000156
157 The abstract base classes also provide default implementations of some
158 methods in order to help implementation of concrete stream classes. For
159 example, :class:`BufferedIOBase` provides unoptimized implementations of
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300160 :meth:`~IOBase.readinto` and :meth:`~IOBase.readline`.
Antoine Pitroub530e142010-08-30 12:41:00 +0000161
162At the top of the I/O hierarchy is the abstract base class :class:`IOBase`. It
163defines the basic interface to a stream. Note, however, that there is no
164separation between reading and writing to streams; implementations are allowed
Benjamin Peterson6b4fa772010-08-30 13:19:53 +0000165to raise :exc:`UnsupportedOperation` if they do not support a given operation.
Antoine Pitroub530e142010-08-30 12:41:00 +0000166
Benjamin Peterson6b4fa772010-08-30 13:19:53 +0000167The :class:`RawIOBase` ABC extends :class:`IOBase`. It deals with the reading
168and writing of bytes to a stream. :class:`FileIO` subclasses :class:`RawIOBase`
169to provide an interface to files in the machine's file system.
Antoine Pitroub530e142010-08-30 12:41:00 +0000170
171The :class:`BufferedIOBase` ABC deals with buffering on a raw byte stream
172(:class:`RawIOBase`). Its subclasses, :class:`BufferedWriter`,
173:class:`BufferedReader`, and :class:`BufferedRWPair` buffer streams that are
Benjamin Peterson6b4fa772010-08-30 13:19:53 +0000174readable, writable, and both readable and writable. :class:`BufferedRandom`
175provides a buffered interface to random access streams. Another
Georg Brandl682d7e02010-10-06 10:26:05 +0000176:class:`BufferedIOBase` subclass, :class:`BytesIO`, is a stream of in-memory
Benjamin Peterson6b4fa772010-08-30 13:19:53 +0000177bytes.
Antoine Pitroub530e142010-08-30 12:41:00 +0000178
Benjamin Peterson6b4fa772010-08-30 13:19:53 +0000179The :class:`TextIOBase` ABC, another subclass of :class:`IOBase`, deals with
180streams whose bytes represent text, and handles encoding and decoding to and
181from strings. :class:`TextIOWrapper`, which extends it, is a buffered text
182interface to a buffered raw stream (:class:`BufferedIOBase`). Finally,
183:class:`StringIO` is an in-memory stream for text.
Antoine Pitroub530e142010-08-30 12:41:00 +0000184
185Argument names are not part of the specification, and only the arguments of
Benjamin Peterson6b4fa772010-08-30 13:19:53 +0000186:func:`open` are intended to be used as keyword arguments.
Antoine Pitroub530e142010-08-30 12:41:00 +0000187
Andrew Svetloved636a82012-12-06 12:20:56 +0200188The following table summarizes the ABCs provided by the :mod:`io` module:
189
Georg Brandl44ea77b2013-03-28 13:28:44 +0100190.. tabularcolumns:: |l|l|L|L|
191
Andrew Svetloved636a82012-12-06 12:20:56 +0200192========================= ================== ======================== ==================================================
193ABC Inherits Stub Methods Mixin Methods and Properties
194========================= ================== ======================== ==================================================
195:class:`IOBase` ``fileno``, ``seek``, ``close``, ``closed``, ``__enter__``,
196 and ``truncate`` ``__exit__``, ``flush``, ``isatty``, ``__iter__``,
197 ``__next__``, ``readable``, ``readline``,
198 ``readlines``, ``seekable``, ``tell``,
199 ``writable``, and ``writelines``
200:class:`RawIOBase` :class:`IOBase` ``readinto`` and Inherited :class:`IOBase` methods, ``read``,
201 ``write`` and ``readall``
202:class:`BufferedIOBase` :class:`IOBase` ``detach``, ``read``, Inherited :class:`IOBase` methods, ``readinto``
203 ``read1``, and ``write``
204:class:`TextIOBase` :class:`IOBase` ``detach``, ``read``, Inherited :class:`IOBase` methods, ``encoding``,
205 ``readline``, and ``errors``, and ``newlines``
206 ``write``
207========================= ================== ======================== ==================================================
208
Antoine Pitroub530e142010-08-30 12:41:00 +0000209
Georg Brandl014197c2008-04-09 18:40:51 +0000210I/O Base Classes
Antoine Pitroub530e142010-08-30 12:41:00 +0000211^^^^^^^^^^^^^^^^
Georg Brandl014197c2008-04-09 18:40:51 +0000212
213.. class:: IOBase
214
215 The abstract base class for all I/O classes, acting on streams of bytes.
216 There is no public constructor.
217
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000218 This class provides empty abstract implementations for many methods
219 that derived classes can override selectively; the default
220 implementations represent a file that cannot be read, written or
221 seeked.
Georg Brandl014197c2008-04-09 18:40:51 +0000222
223 Even though :class:`IOBase` does not declare :meth:`read`, :meth:`readinto`,
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000224 or :meth:`write` because their signatures will vary, implementations and
225 clients should consider those methods part of the interface. Also,
Antoine Pitroua787b652011-10-12 19:02:52 +0200226 implementations may raise a :exc:`ValueError` (or :exc:`UnsupportedOperation`)
227 when operations they do not support are called.
Georg Brandl014197c2008-04-09 18:40:51 +0000228
229 The basic type used for binary data read from or written to a file is
230 :class:`bytes`. :class:`bytearray`\s are accepted too, and in some cases
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300231 (such as :meth:`readinto`) required. Text I/O classes work with
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000232 :class:`str` data.
Georg Brandl014197c2008-04-09 18:40:51 +0000233
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000234 Note that calling any method (even inquiries) on a closed stream is
Antoine Pitroua787b652011-10-12 19:02:52 +0200235 undefined. Implementations may raise :exc:`ValueError` in this case.
Georg Brandl014197c2008-04-09 18:40:51 +0000236
Éric Araujo3f7c0e42012-12-08 22:53:43 -0500237 :class:`IOBase` (and its subclasses) supports the iterator protocol, meaning
Eli Benderskyf877a7c2012-07-14 21:22:25 +0300238 that an :class:`IOBase` object can be iterated over yielding the lines in a
239 stream. Lines are defined slightly differently depending on whether the
240 stream is a binary stream (yielding bytes), or a text stream (yielding
241 character strings). See :meth:`~IOBase.readline` below.
Georg Brandl014197c2008-04-09 18:40:51 +0000242
Eli Benderskyf877a7c2012-07-14 21:22:25 +0300243 :class:`IOBase` is also a context manager and therefore supports the
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000244 :keyword:`with` statement. In this example, *file* is closed after the
245 :keyword:`with` statement's suite is finished---even if an exception occurs::
Georg Brandl014197c2008-04-09 18:40:51 +0000246
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000247 with open('spam.txt', 'w') as file:
248 file.write('Spam and eggs!')
Georg Brandl014197c2008-04-09 18:40:51 +0000249
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000250 :class:`IOBase` provides these data attributes and methods:
Georg Brandl014197c2008-04-09 18:40:51 +0000251
252 .. method:: close()
253
Christian Heimesecc42a22008-11-05 19:30:32 +0000254 Flush and close this stream. This method has no effect if the file is
Georg Brandl48310cd2009-01-03 21:18:54 +0000255 already closed. Once the file is closed, any operation on the file
Georg Brandl8569e582010-05-19 20:57:08 +0000256 (e.g. reading or writing) will raise a :exc:`ValueError`.
Antoine Pitrouf9fc08f2010-04-28 19:59:32 +0000257
258 As a convenience, it is allowed to call this method more than once;
259 only the first call, however, will have an effect.
Georg Brandl014197c2008-04-09 18:40:51 +0000260
261 .. attribute:: closed
262
Eli Benderskyf877a7c2012-07-14 21:22:25 +0300263 ``True`` if the stream is closed.
Georg Brandl014197c2008-04-09 18:40:51 +0000264
265 .. method:: fileno()
266
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000267 Return the underlying file descriptor (an integer) of the stream if it
Antoine Pitroua787b652011-10-12 19:02:52 +0200268 exists. An :exc:`OSError` is raised if the IO object does not use a file
Georg Brandl014197c2008-04-09 18:40:51 +0000269 descriptor.
270
271 .. method:: flush()
272
Benjamin Petersonb85a5842008-04-13 21:39:58 +0000273 Flush the write buffers of the stream if applicable. This does nothing
274 for read-only and non-blocking streams.
Georg Brandl014197c2008-04-09 18:40:51 +0000275
276 .. method:: isatty()
277
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000278 Return ``True`` if the stream is interactive (i.e., connected to
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000279 a terminal/tty device).
Georg Brandl014197c2008-04-09 18:40:51 +0000280
281 .. method:: readable()
282
Serhiy Storchakafbc1c262013-11-29 12:17:13 +0200283 Return ``True`` if the stream can be read from. If ``False``, :meth:`read`
Antoine Pitroua787b652011-10-12 19:02:52 +0200284 will raise :exc:`OSError`.
Georg Brandl014197c2008-04-09 18:40:51 +0000285
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300286 .. method:: readline(size=-1)
Georg Brandl014197c2008-04-09 18:40:51 +0000287
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300288 Read and return one line from the stream. If *size* is specified, at
289 most *size* bytes will be read.
Georg Brandl014197c2008-04-09 18:40:51 +0000290
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000291 The line terminator is always ``b'\n'`` for binary files; for text files,
Benjamin Peterson6b4fa772010-08-30 13:19:53 +0000292 the *newlines* argument to :func:`open` can be used to select the line
Georg Brandl014197c2008-04-09 18:40:51 +0000293 terminator(s) recognized.
294
Georg Brandl3dd33882009-06-01 17:35:27 +0000295 .. method:: readlines(hint=-1)
Georg Brandl014197c2008-04-09 18:40:51 +0000296
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000297 Read and return a list of lines from the stream. *hint* can be specified
298 to control the number of lines read: no more lines will be read if the
299 total size (in bytes/characters) of all lines so far exceeds *hint*.
Georg Brandl014197c2008-04-09 18:40:51 +0000300
Ezio Melottied3cd7e2013-04-15 19:08:31 +0300301 Note that it's already possible to iterate on file objects using ``for
302 line in file: ...`` without calling ``file.readlines()``.
303
Georg Brandl3dd33882009-06-01 17:35:27 +0000304 .. method:: seek(offset, whence=SEEK_SET)
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000305
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000306 Change the stream position to the given byte *offset*. *offset* is
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000307 interpreted relative to the position indicated by *whence*. Values for
308 *whence* are:
309
Benjamin Peterson0e4caf42009-04-01 21:22:20 +0000310 * :data:`SEEK_SET` or ``0`` -- start of the stream (the default);
311 *offset* should be zero or positive
312 * :data:`SEEK_CUR` or ``1`` -- current stream position; *offset* may
313 be negative
314 * :data:`SEEK_END` or ``2`` -- end of the stream; *offset* is usually
315 negative
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000316
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000317 Return the new absolute position.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000318
Raymond Hettinger35a88362009-04-09 00:08:24 +0000319 .. versionadded:: 3.1
Georg Brandl67b21b72010-08-17 15:07:14 +0000320 The ``SEEK_*`` constants.
Benjamin Peterson0e4caf42009-04-01 21:22:20 +0000321
Jesus Cea94363612012-06-22 18:32:07 +0200322 .. versionadded:: 3.3
323 Some operating systems could support additional values, like
324 :data:`os.SEEK_HOLE` or :data:`os.SEEK_DATA`. The valid values
325 for a file could depend on it being open in text or binary mode.
326
Georg Brandl014197c2008-04-09 18:40:51 +0000327 .. method:: seekable()
328
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000329 Return ``True`` if the stream supports random access. If ``False``,
Antoine Pitroua787b652011-10-12 19:02:52 +0200330 :meth:`seek`, :meth:`tell` and :meth:`truncate` will raise :exc:`OSError`.
Georg Brandl014197c2008-04-09 18:40:51 +0000331
332 .. method:: tell()
333
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000334 Return the current stream position.
Georg Brandl014197c2008-04-09 18:40:51 +0000335
Georg Brandl3dd33882009-06-01 17:35:27 +0000336 .. method:: truncate(size=None)
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000337
Antoine Pitrou2016dc92010-05-29 12:08:25 +0000338 Resize the stream to the given *size* in bytes (or the current position
339 if *size* is not specified). The current stream position isn't changed.
340 This resizing can extend or reduce the current file size. In case of
341 extension, the contents of the new file area depend on the platform
342 (on most systems, additional bytes are zero-filled, on Windows they're
343 undetermined). The new file size is returned.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000344
Georg Brandl014197c2008-04-09 18:40:51 +0000345 .. method:: writable()
346
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000347 Return ``True`` if the stream supports writing. If ``False``,
Antoine Pitroua787b652011-10-12 19:02:52 +0200348 :meth:`write` and :meth:`truncate` will raise :exc:`OSError`.
Georg Brandl014197c2008-04-09 18:40:51 +0000349
350 .. method:: writelines(lines)
351
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000352 Write a list of lines to the stream. Line separators are not added, so it
353 is usual for each of the lines provided to have a line separator at the
354 end.
Georg Brandl014197c2008-04-09 18:40:51 +0000355
356
357.. class:: RawIOBase
358
359 Base class for raw binary I/O. It inherits :class:`IOBase`. There is no
360 public constructor.
361
Antoine Pitrou497a7672009-09-17 17:18:01 +0000362 Raw binary I/O typically provides low-level access to an underlying OS
363 device or API, and does not try to encapsulate it in high-level primitives
364 (this is left to Buffered I/O and Text I/O, described later in this page).
365
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000366 In addition to the attributes and methods from :class:`IOBase`,
Eli Benderskyf877a7c2012-07-14 21:22:25 +0300367 :class:`RawIOBase` provides the following methods:
Georg Brandl014197c2008-04-09 18:40:51 +0000368
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300369 .. method:: read(size=-1)
Georg Brandl014197c2008-04-09 18:40:51 +0000370
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300371 Read up to *size* bytes from the object and return them. As a convenience,
372 if *size* is unspecified or -1, :meth:`readall` is called. Otherwise,
373 only one system call is ever made. Fewer than *size* bytes may be
374 returned if the operating system call returns fewer than *size* bytes.
Antoine Pitrou78ddbe62009-10-01 16:24:45 +0000375
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300376 If 0 bytes are returned, and *size* was not 0, this indicates end of file.
Antoine Pitrou78ddbe62009-10-01 16:24:45 +0000377 If the object is in non-blocking mode and no bytes are available,
378 ``None`` is returned.
Georg Brandl014197c2008-04-09 18:40:51 +0000379
Benjamin Petersonb47aace2008-04-09 21:38:38 +0000380 .. method:: readall()
Georg Brandl014197c2008-04-09 18:40:51 +0000381
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000382 Read and return all the bytes from the stream until EOF, using multiple
383 calls to the stream if necessary.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000384
385 .. method:: readinto(b)
386
Eli Benderskyf877a7c2012-07-14 21:22:25 +0300387 Read up to ``len(b)`` bytes into :class:`bytearray` *b* and return the
388 number of bytes read. If the object is in non-blocking mode and no
Daniel Stutzbachd01df462010-11-30 17:49:53 +0000389 bytes are available, ``None`` is returned.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000390
391 .. method:: write(b)
392
Eli Benderskyf877a7c2012-07-14 21:22:25 +0300393 Write the given :class:`bytes` or :class:`bytearray` object, *b*, to the
394 underlying raw stream and return the number of bytes written. This can
395 be less than ``len(b)``, depending on specifics of the underlying raw
396 stream, and especially if it is in non-blocking mode. ``None`` is
397 returned if the raw stream is set not to block and no single byte could
398 be readily written to it.
Georg Brandl014197c2008-04-09 18:40:51 +0000399
400
Georg Brandl014197c2008-04-09 18:40:51 +0000401.. class:: BufferedIOBase
402
Antoine Pitrou497a7672009-09-17 17:18:01 +0000403 Base class for binary streams that support some kind of buffering.
404 It inherits :class:`IOBase`. There is no public constructor.
Georg Brandl014197c2008-04-09 18:40:51 +0000405
Antoine Pitrou497a7672009-09-17 17:18:01 +0000406 The main difference with :class:`RawIOBase` is that methods :meth:`read`,
407 :meth:`readinto` and :meth:`write` will try (respectively) to read as much
408 input as requested or to consume all given output, at the expense of
409 making perhaps more than one system call.
410
411 In addition, those methods can raise :exc:`BlockingIOError` if the
412 underlying raw stream is in non-blocking mode and cannot take or give
413 enough data; unlike their :class:`RawIOBase` counterparts, they will
414 never return ``None``.
415
416 Besides, the :meth:`read` method does not have a default
Georg Brandl014197c2008-04-09 18:40:51 +0000417 implementation that defers to :meth:`readinto`.
418
Antoine Pitrou497a7672009-09-17 17:18:01 +0000419 A typical :class:`BufferedIOBase` implementation should not inherit from a
420 :class:`RawIOBase` implementation, but wrap one, like
421 :class:`BufferedWriter` and :class:`BufferedReader` do.
Georg Brandl014197c2008-04-09 18:40:51 +0000422
Senthil Kumarana6bac952011-07-04 11:28:30 -0700423 :class:`BufferedIOBase` provides or overrides these methods and attribute in
424 addition to those from :class:`IOBase`:
Georg Brandl014197c2008-04-09 18:40:51 +0000425
Benjamin Petersonc609b6b2009-06-28 17:32:20 +0000426 .. attribute:: raw
427
428 The underlying raw stream (a :class:`RawIOBase` instance) that
429 :class:`BufferedIOBase` deals with. This is not part of the
430 :class:`BufferedIOBase` API and may not exist on some implementations.
431
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000432 .. method:: detach()
433
434 Separate the underlying raw stream from the buffer and return it.
435
436 After the raw stream has been detached, the buffer is in an unusable
437 state.
438
439 Some buffers, like :class:`BytesIO`, do not have the concept of a single
440 raw stream to return from this method. They raise
441 :exc:`UnsupportedOperation`.
442
Benjamin Petersonedc36472009-05-01 20:48:14 +0000443 .. versionadded:: 3.1
444
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300445 .. method:: read(size=-1)
Georg Brandl014197c2008-04-09 18:40:51 +0000446
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300447 Read and return up to *size* bytes. If the argument is omitted, ``None``,
448 or negative, data is read and returned until EOF is reached. An empty
Eli Benderskyf877a7c2012-07-14 21:22:25 +0300449 :class:`bytes` object is returned if the stream is already at EOF.
Georg Brandl014197c2008-04-09 18:40:51 +0000450
451 If the argument is positive, and the underlying raw stream is not
452 interactive, multiple raw reads may be issued to satisfy the byte count
453 (unless EOF is reached first). But for interactive raw streams, at most
454 one raw read will be issued, and a short result does not imply that EOF is
455 imminent.
456
Antoine Pitrou497a7672009-09-17 17:18:01 +0000457 A :exc:`BlockingIOError` is raised if the underlying raw stream is in
458 non blocking-mode, and has no data available at the moment.
Georg Brandl014197c2008-04-09 18:40:51 +0000459
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300460 .. method:: read1(size=-1)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000461
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300462 Read and return up to *size* bytes, with at most one call to the underlying
Antoine Pitrou497a7672009-09-17 17:18:01 +0000463 raw stream's :meth:`~RawIOBase.read` method. This can be useful if you
464 are implementing your own buffering on top of a :class:`BufferedIOBase`
465 object.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000466
Georg Brandl014197c2008-04-09 18:40:51 +0000467 .. method:: readinto(b)
468
Eli Benderskyf877a7c2012-07-14 21:22:25 +0300469 Read up to ``len(b)`` bytes into bytearray *b* and return the number of
470 bytes read.
Georg Brandl014197c2008-04-09 18:40:51 +0000471
472 Like :meth:`read`, multiple reads may be issued to the underlying raw
Eli Benderskyf877a7c2012-07-14 21:22:25 +0300473 stream, unless the latter is interactive.
Georg Brandl014197c2008-04-09 18:40:51 +0000474
Antoine Pitrou497a7672009-09-17 17:18:01 +0000475 A :exc:`BlockingIOError` is raised if the underlying raw stream is in
476 non blocking-mode, and has no data available at the moment.
Georg Brandl014197c2008-04-09 18:40:51 +0000477
Georg Brandl014197c2008-04-09 18:40:51 +0000478 .. method:: write(b)
479
Eli Benderskyf877a7c2012-07-14 21:22:25 +0300480 Write the given :class:`bytes` or :class:`bytearray` object, *b* and
481 return the number of bytes written (never less than ``len(b)``, since if
482 the write fails an :exc:`OSError` will be raised). Depending on the
483 actual implementation, these bytes may be readily written to the
484 underlying stream, or held in a buffer for performance and latency
485 reasons.
Georg Brandl014197c2008-04-09 18:40:51 +0000486
Antoine Pitrou497a7672009-09-17 17:18:01 +0000487 When in non-blocking mode, a :exc:`BlockingIOError` is raised if the
488 data needed to be written to the raw stream but it couldn't accept
489 all the data without blocking.
Georg Brandl014197c2008-04-09 18:40:51 +0000490
491
Benjamin Petersonaa069002009-01-23 03:26:36 +0000492Raw File I/O
Antoine Pitroub530e142010-08-30 12:41:00 +0000493^^^^^^^^^^^^
Benjamin Petersonaa069002009-01-23 03:26:36 +0000494
Ross Lagerwall59142db2011-10-31 20:34:46 +0200495.. class:: FileIO(name, mode='r', closefd=True, opener=None)
Benjamin Petersonaa069002009-01-23 03:26:36 +0000496
Antoine Pitrou497a7672009-09-17 17:18:01 +0000497 :class:`FileIO` represents an OS-level file containing bytes data.
498 It implements the :class:`RawIOBase` interface (and therefore the
499 :class:`IOBase` interface, too).
500
501 The *name* can be one of two things:
502
Eli Benderskyf877a7c2012-07-14 21:22:25 +0300503 * a character string or :class:`bytes` object representing the path to the
504 file which will be opened;
Antoine Pitrou497a7672009-09-17 17:18:01 +0000505 * an integer representing the number of an existing OS-level file descriptor
506 to which the resulting :class:`FileIO` object will give access.
Benjamin Petersonaa069002009-01-23 03:26:36 +0000507
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100508 The *mode* can be ``'r'``, ``'w'``, ``'x'`` or ``'a'`` for reading
Charles-François Natalid612de12012-01-14 11:51:00 +0100509 (default), writing, exclusive creation or appending. The file will be
510 created if it doesn't exist when opened for writing or appending; it will be
511 truncated when opened for writing. :exc:`FileExistsError` will be raised if
512 it already exists when opened for creating. Opening a file for creating
513 implies writing, so this mode behaves in a similar way to ``'w'``. Add a
514 ``'+'`` to the mode to allow simultaneous reading and writing.
Benjamin Petersonaa069002009-01-23 03:26:36 +0000515
Antoine Pitrou497a7672009-09-17 17:18:01 +0000516 The :meth:`read` (when called with a positive argument), :meth:`readinto`
517 and :meth:`write` methods on this class will only make one system call.
518
Ross Lagerwall59142db2011-10-31 20:34:46 +0200519 A custom opener can be used by passing a callable as *opener*. The underlying
520 file descriptor for the file object is then obtained by calling *opener* with
521 (*name*, *flags*). *opener* must return an open file descriptor (passing
522 :mod:`os.open` as *opener* results in functionality similar to passing
523 ``None``).
524
Victor Stinnerdaf45552013-08-28 00:53:59 +0200525 The newly created file is :ref:`non-inheritable <fd_inheritance>`.
526
Éric Araujo8f423c92012-11-03 17:06:52 -0400527 See the :func:`open` built-in function for examples on using the *opener*
528 parameter.
529
Ross Lagerwall59142db2011-10-31 20:34:46 +0200530 .. versionchanged:: 3.3
531 The *opener* parameter was added.
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100532 The ``'x'`` mode was added.
Ross Lagerwall59142db2011-10-31 20:34:46 +0200533
Victor Stinnerdaf45552013-08-28 00:53:59 +0200534 .. versionchanged:: 3.4
535 The file is now non-inheritable.
536
Benjamin Petersonaa069002009-01-23 03:26:36 +0000537 In addition to the attributes and methods from :class:`IOBase` and
538 :class:`RawIOBase`, :class:`FileIO` provides the following data
Eli Benderskyf877a7c2012-07-14 21:22:25 +0300539 attributes:
Benjamin Petersonaa069002009-01-23 03:26:36 +0000540
541 .. attribute:: mode
542
543 The mode as given in the constructor.
544
545 .. attribute:: name
546
547 The file name. This is the file descriptor of the file when no name is
548 given in the constructor.
549
Benjamin Petersonaa069002009-01-23 03:26:36 +0000550
551Buffered Streams
Antoine Pitroub530e142010-08-30 12:41:00 +0000552^^^^^^^^^^^^^^^^
Benjamin Petersonaa069002009-01-23 03:26:36 +0000553
Antoine Pitroubed81c82010-12-03 19:14:17 +0000554Buffered I/O streams provide a higher-level interface to an I/O device
555than raw I/O does.
Antoine Pitrou497a7672009-09-17 17:18:01 +0000556
Georg Brandl014197c2008-04-09 18:40:51 +0000557.. class:: BytesIO([initial_bytes])
558
559 A stream implementation using an in-memory bytes buffer. It inherits
560 :class:`BufferedIOBase`.
561
Antoine Pitroub530e142010-08-30 12:41:00 +0000562 The argument *initial_bytes* contains optional initial :class:`bytes` data.
Georg Brandl014197c2008-04-09 18:40:51 +0000563
564 :class:`BytesIO` provides or overrides these methods in addition to those
565 from :class:`BufferedIOBase` and :class:`IOBase`:
566
Antoine Pitrou972ee132010-09-06 18:48:21 +0000567 .. method:: getbuffer()
568
569 Return a readable and writable view over the contents of the buffer
570 without copying them. Also, mutating the view will transparently
571 update the contents of the buffer::
572
573 >>> b = io.BytesIO(b"abcdef")
574 >>> view = b.getbuffer()
575 >>> view[2:4] = b"56"
576 >>> b.getvalue()
577 b'ab56ef'
578
579 .. note::
580 As long as the view exists, the :class:`BytesIO` object cannot be
581 resized.
582
583 .. versionadded:: 3.2
584
Georg Brandl014197c2008-04-09 18:40:51 +0000585 .. method:: getvalue()
586
Eli Benderskyf877a7c2012-07-14 21:22:25 +0300587 Return :class:`bytes` containing the entire contents of the buffer.
Georg Brandl014197c2008-04-09 18:40:51 +0000588
589 .. method:: read1()
590
Benjamin Peterson9efcc4b2008-04-14 21:30:21 +0000591 In :class:`BytesIO`, this is the same as :meth:`read`.
Georg Brandl014197c2008-04-09 18:40:51 +0000592
Georg Brandl014197c2008-04-09 18:40:51 +0000593
Georg Brandl3dd33882009-06-01 17:35:27 +0000594.. class:: BufferedReader(raw, buffer_size=DEFAULT_BUFFER_SIZE)
Georg Brandl014197c2008-04-09 18:40:51 +0000595
Antoine Pitrou497a7672009-09-17 17:18:01 +0000596 A buffer providing higher-level access to a readable, sequential
597 :class:`RawIOBase` object. It inherits :class:`BufferedIOBase`.
598 When reading data from this object, a larger amount of data may be
599 requested from the underlying raw stream, and kept in an internal buffer.
600 The buffered data can then be returned directly on subsequent reads.
Georg Brandl014197c2008-04-09 18:40:51 +0000601
602 The constructor creates a :class:`BufferedReader` for the given readable
603 *raw* stream and *buffer_size*. If *buffer_size* is omitted,
604 :data:`DEFAULT_BUFFER_SIZE` is used.
605
606 :class:`BufferedReader` provides or overrides these methods in addition to
607 those from :class:`BufferedIOBase` and :class:`IOBase`:
608
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300609 .. method:: peek([size])
Georg Brandl014197c2008-04-09 18:40:51 +0000610
Benjamin Petersonc43a26d2009-06-16 23:09:24 +0000611 Return bytes from the stream without advancing the position. At most one
Benjamin Peterson2a8b54d2009-06-14 14:37:23 +0000612 single read on the raw stream is done to satisfy the call. The number of
613 bytes returned may be less or more than requested.
Georg Brandl014197c2008-04-09 18:40:51 +0000614
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300615 .. method:: read([size])
Georg Brandl014197c2008-04-09 18:40:51 +0000616
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300617 Read and return *size* bytes, or if *size* is not given or negative, until
618 EOF or if the read call would block in non-blocking mode.
Georg Brandl014197c2008-04-09 18:40:51 +0000619
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300620 .. method:: read1(size)
Georg Brandl014197c2008-04-09 18:40:51 +0000621
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300622 Read and return up to *size* bytes with only one call on the raw stream.
623 If at least one byte is buffered, only buffered bytes are returned.
Georg Brandl014197c2008-04-09 18:40:51 +0000624 Otherwise, one raw stream read call is made.
625
626
Georg Brandl3dd33882009-06-01 17:35:27 +0000627.. class:: BufferedWriter(raw, buffer_size=DEFAULT_BUFFER_SIZE)
Georg Brandl014197c2008-04-09 18:40:51 +0000628
Antoine Pitrou497a7672009-09-17 17:18:01 +0000629 A buffer providing higher-level access to a writeable, sequential
630 :class:`RawIOBase` object. It inherits :class:`BufferedIOBase`.
Eli Benderskyf877a7c2012-07-14 21:22:25 +0300631 When writing to this object, data is normally placed into an internal
Antoine Pitrou497a7672009-09-17 17:18:01 +0000632 buffer. The buffer will be written out to the underlying :class:`RawIOBase`
633 object under various conditions, including:
634
635 * when the buffer gets too small for all pending data;
636 * when :meth:`flush()` is called;
637 * when a :meth:`seek()` is requested (for :class:`BufferedRandom` objects);
638 * when the :class:`BufferedWriter` object is closed or destroyed.
Georg Brandl014197c2008-04-09 18:40:51 +0000639
640 The constructor creates a :class:`BufferedWriter` for the given writeable
641 *raw* stream. If the *buffer_size* is not given, it defaults to
Benjamin Peterson394ee002009-03-05 22:33:59 +0000642 :data:`DEFAULT_BUFFER_SIZE`.
643
Georg Brandl014197c2008-04-09 18:40:51 +0000644 :class:`BufferedWriter` provides or overrides these methods in addition to
645 those from :class:`BufferedIOBase` and :class:`IOBase`:
646
647 .. method:: flush()
648
649 Force bytes held in the buffer into the raw stream. A
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000650 :exc:`BlockingIOError` should be raised if the raw stream blocks.
Georg Brandl014197c2008-04-09 18:40:51 +0000651
652 .. method:: write(b)
653
Eli Benderskyf877a7c2012-07-14 21:22:25 +0300654 Write the :class:`bytes` or :class:`bytearray` object, *b* and return the
655 number of bytes written. When in non-blocking mode, a
656 :exc:`BlockingIOError` is raised if the buffer needs to be written out but
657 the raw stream blocks.
Georg Brandl014197c2008-04-09 18:40:51 +0000658
659
Georg Brandl3dd33882009-06-01 17:35:27 +0000660.. class:: BufferedRandom(raw, buffer_size=DEFAULT_BUFFER_SIZE)
Georg Brandl014197c2008-04-09 18:40:51 +0000661
662 A buffered interface to random access streams. It inherits
Antoine Pitrou497a7672009-09-17 17:18:01 +0000663 :class:`BufferedReader` and :class:`BufferedWriter`, and further supports
664 :meth:`seek` and :meth:`tell` functionality.
Georg Brandl014197c2008-04-09 18:40:51 +0000665
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000666 The constructor creates a reader and writer for a seekable raw stream, given
Georg Brandl014197c2008-04-09 18:40:51 +0000667 in the first argument. If the *buffer_size* is omitted it defaults to
Benjamin Peterson394ee002009-03-05 22:33:59 +0000668 :data:`DEFAULT_BUFFER_SIZE`.
669
Georg Brandl014197c2008-04-09 18:40:51 +0000670 :class:`BufferedRandom` is capable of anything :class:`BufferedReader` or
671 :class:`BufferedWriter` can do.
672
673
Antoine Pitrou13d28952011-08-20 19:48:43 +0200674.. class:: BufferedRWPair(reader, writer, buffer_size=DEFAULT_BUFFER_SIZE)
675
676 A buffered I/O object combining two unidirectional :class:`RawIOBase`
677 objects -- one readable, the other writeable -- into a single bidirectional
678 endpoint. It inherits :class:`BufferedIOBase`.
679
680 *reader* and *writer* are :class:`RawIOBase` objects that are readable and
681 writeable respectively. If the *buffer_size* is omitted it defaults to
682 :data:`DEFAULT_BUFFER_SIZE`.
683
Antoine Pitrou13d28952011-08-20 19:48:43 +0200684 :class:`BufferedRWPair` implements all of :class:`BufferedIOBase`\'s methods
685 except for :meth:`~BufferedIOBase.detach`, which raises
686 :exc:`UnsupportedOperation`.
687
688 .. warning::
689 :class:`BufferedRWPair` does not attempt to synchronize accesses to
690 its underlying raw streams. You should not pass it the same object
691 as reader and writer; use :class:`BufferedRandom` instead.
692
693
Georg Brandl014197c2008-04-09 18:40:51 +0000694Text I/O
Antoine Pitroub530e142010-08-30 12:41:00 +0000695^^^^^^^^
Georg Brandl014197c2008-04-09 18:40:51 +0000696
697.. class:: TextIOBase
698
699 Base class for text streams. This class provides a character and line based
700 interface to stream I/O. There is no :meth:`readinto` method because
701 Python's character strings are immutable. It inherits :class:`IOBase`.
702 There is no public constructor.
703
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000704 :class:`TextIOBase` provides or overrides these data attributes and
705 methods in addition to those from :class:`IOBase`:
Georg Brandl014197c2008-04-09 18:40:51 +0000706
707 .. attribute:: encoding
708
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000709 The name of the encoding used to decode the stream's bytes into
Georg Brandl014197c2008-04-09 18:40:51 +0000710 strings, and to encode strings into bytes.
711
Benjamin Peterson0926ad12009-06-06 18:02:12 +0000712 .. attribute:: errors
713
714 The error setting of the decoder or encoder.
715
Georg Brandl014197c2008-04-09 18:40:51 +0000716 .. attribute:: newlines
717
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000718 A string, a tuple of strings, or ``None``, indicating the newlines
Antoine Pitrou497a7672009-09-17 17:18:01 +0000719 translated so far. Depending on the implementation and the initial
720 constructor flags, this may not be available.
Georg Brandl014197c2008-04-09 18:40:51 +0000721
Benjamin Petersonc609b6b2009-06-28 17:32:20 +0000722 .. attribute:: buffer
723
724 The underlying binary buffer (a :class:`BufferedIOBase` instance) that
725 :class:`TextIOBase` deals with. This is not part of the
Eli Benderskyf877a7c2012-07-14 21:22:25 +0300726 :class:`TextIOBase` API and may not exist in some implementations.
Benjamin Petersonc609b6b2009-06-28 17:32:20 +0000727
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000728 .. method:: detach()
729
Antoine Pitrou497a7672009-09-17 17:18:01 +0000730 Separate the underlying binary buffer from the :class:`TextIOBase` and
731 return it.
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000732
733 After the underlying buffer has been detached, the :class:`TextIOBase` is
734 in an unusable state.
735
736 Some :class:`TextIOBase` implementations, like :class:`StringIO`, may not
737 have the concept of an underlying buffer and calling this method will
738 raise :exc:`UnsupportedOperation`.
739
Benjamin Petersonedc36472009-05-01 20:48:14 +0000740 .. versionadded:: 3.1
741
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300742 .. method:: read(size)
Georg Brandl014197c2008-04-09 18:40:51 +0000743
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300744 Read and return at most *size* characters from the stream as a single
745 :class:`str`. If *size* is negative or ``None``, reads until EOF.
Georg Brandl014197c2008-04-09 18:40:51 +0000746
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300747 .. method:: readline(size=-1)
Georg Brandl014197c2008-04-09 18:40:51 +0000748
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000749 Read until newline or EOF and return a single ``str``. If the stream is
750 already at EOF, an empty string is returned.
Georg Brandl014197c2008-04-09 18:40:51 +0000751
Serhiy Storchaka3c411542013-09-16 23:18:10 +0300752 If *size* is specified, at most *size* characters will be read.
Antoine Pitrou707bd4e2012-07-25 22:38:33 +0200753
Antoine Pitrouf49d1522012-01-21 20:20:49 +0100754 .. method:: seek(offset, whence=SEEK_SET)
755
756 Change the stream position to the given *offset*. Behaviour depends
757 on the *whence* parameter:
758
759 * :data:`SEEK_SET` or ``0``: seek from the start of the stream
760 (the default); *offset* must either be a number returned by
761 :meth:`TextIOBase.tell`, or zero. Any other *offset* value
762 produces undefined behaviour.
763 * :data:`SEEK_CUR` or ``1``: "seek" to the current position;
764 *offset* must be zero, which is a no-operation (all other values
765 are unsupported).
766 * :data:`SEEK_END` or ``2``: seek to the end of the stream;
767 *offset* must be zero (all other values are unsupported).
768
769 Return the new absolute position as an opaque number.
770
771 .. versionadded:: 3.1
772 The ``SEEK_*`` constants.
773
774 .. method:: tell()
775
776 Return the current stream position as an opaque number. The number
777 does not usually represent a number of bytes in the underlying
778 binary storage.
779
Georg Brandl014197c2008-04-09 18:40:51 +0000780 .. method:: write(s)
781
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000782 Write the string *s* to the stream and return the number of characters
783 written.
Georg Brandl014197c2008-04-09 18:40:51 +0000784
785
Antoine Pitrou664091b2011-07-23 22:00:03 +0200786.. class:: TextIOWrapper(buffer, encoding=None, errors=None, newline=None, \
787 line_buffering=False, write_through=False)
Georg Brandl014197c2008-04-09 18:40:51 +0000788
Antoine Pitrou497a7672009-09-17 17:18:01 +0000789 A buffered text stream over a :class:`BufferedIOBase` binary stream.
Georg Brandl014197c2008-04-09 18:40:51 +0000790 It inherits :class:`TextIOBase`.
791
792 *encoding* gives the name of the encoding that the stream will be decoded or
Andrew Svetlov4805fa82012-08-13 22:11:14 +0300793 encoded with. It defaults to
794 :func:`locale.getpreferredencoding(False) <locale.getpreferredencoding>`.
Georg Brandl014197c2008-04-09 18:40:51 +0000795
Benjamin Petersonb85a5842008-04-13 21:39:58 +0000796 *errors* is an optional string that specifies how encoding and decoding
797 errors are to be handled. Pass ``'strict'`` to raise a :exc:`ValueError`
798 exception if there is an encoding error (the default of ``None`` has the same
799 effect), or pass ``'ignore'`` to ignore errors. (Note that ignoring encoding
800 errors can lead to data loss.) ``'replace'`` causes a replacement marker
Christian Heimesa342c012008-04-20 21:01:16 +0000801 (such as ``'?'``) to be inserted where there is malformed data. When
802 writing, ``'xmlcharrefreplace'`` (replace with the appropriate XML character
803 reference) or ``'backslashreplace'`` (replace with backslashed escape
804 sequences) can be used. Any other error handling name that has been
805 registered with :func:`codecs.register_error` is also valid.
Georg Brandl014197c2008-04-09 18:40:51 +0000806
R David Murray1b00f252012-08-15 10:43:58 -0400807 .. index::
808 single: universal newlines; io.TextIOWrapper class
809
Antoine Pitrou0c1c0d42012-08-04 00:55:38 +0200810 *newline* controls how line endings are handled. It can be ``None``,
811 ``''``, ``'\n'``, ``'\r'``, and ``'\r\n'``. It works as follows:
812
R David Murray1b00f252012-08-15 10:43:58 -0400813 * When reading input from the stream, if *newline* is ``None``,
R David Murrayee0a9452012-08-15 11:05:36 -0400814 :term:`universal newlines` mode is enabled. Lines in the input can end in
815 ``'\n'``, ``'\r'``, or ``'\r\n'``, and these are translated into ``'\n'``
816 before being returned to the caller. If it is ``''``, universal newlines
817 mode is enabled, but line endings are returned to the caller untranslated.
818 If it has any of the other legal values, input lines are only terminated
819 by the given string, and the line ending is returned to the caller
820 untranslated.
Antoine Pitrou0c1c0d42012-08-04 00:55:38 +0200821
Georg Brandl296d1be2012-08-14 09:39:07 +0200822 * When writing output to the stream, if *newline* is ``None``, any ``'\n'``
823 characters written are translated to the system default line separator,
824 :data:`os.linesep`. If *newline* is ``''`` or ``'\n'``, no translation
825 takes place. If *newline* is any of the other legal values, any ``'\n'``
826 characters written are translated to the given string.
Georg Brandl014197c2008-04-09 18:40:51 +0000827
828 If *line_buffering* is ``True``, :meth:`flush` is implied when a call to
829 write contains a newline character.
830
Antoine Pitrou664091b2011-07-23 22:00:03 +0200831 If *write_through* is ``True``, calls to :meth:`write` are guaranteed
832 not to be buffered: any data written on the :class:`TextIOWrapper`
833 object is immediately handled to its underlying binary *buffer*.
834
835 .. versionchanged:: 3.3
836 The *write_through* argument has been added.
837
Victor Stinnerf86a5e82012-06-05 13:43:22 +0200838 .. versionchanged:: 3.3
839 The default *encoding* is now ``locale.getpreferredencoding(False)``
840 instead of ``locale.getpreferredencoding()``. Don't change temporary the
841 locale encoding using :func:`locale.setlocale`, use the current locale
842 encoding instead of the user preferred encoding.
843
Benjamin Peterson0926ad12009-06-06 18:02:12 +0000844 :class:`TextIOWrapper` provides one attribute in addition to those of
Georg Brandl014197c2008-04-09 18:40:51 +0000845 :class:`TextIOBase` and its parents:
846
Georg Brandl014197c2008-04-09 18:40:51 +0000847 .. attribute:: line_buffering
848
849 Whether line buffering is enabled.
Georg Brandl48310cd2009-01-03 21:18:54 +0000850
Georg Brandl014197c2008-04-09 18:40:51 +0000851
Georg Brandl3dd33882009-06-01 17:35:27 +0000852.. class:: StringIO(initial_value='', newline=None)
Georg Brandl014197c2008-04-09 18:40:51 +0000853
Antoine Pitroub530e142010-08-30 12:41:00 +0000854 An in-memory stream for text I/O.
Georg Brandl014197c2008-04-09 18:40:51 +0000855
Benjamin Petersonaa1c8d82009-03-09 02:02:23 +0000856 The initial value of the buffer (an empty string by default) can be set by
857 providing *initial_value*. The *newline* argument works like that of
858 :class:`TextIOWrapper`. The default is to do no newline translation.
Georg Brandl014197c2008-04-09 18:40:51 +0000859
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000860 :class:`StringIO` provides this method in addition to those from
Antoine Pitroub530e142010-08-30 12:41:00 +0000861 :class:`TextIOBase` and its parents:
Georg Brandl014197c2008-04-09 18:40:51 +0000862
863 .. method:: getvalue()
864
Georg Brandl2932d932008-05-30 06:27:09 +0000865 Return a ``str`` containing the entire contents of the buffer at any
866 time before the :class:`StringIO` object's :meth:`close` method is
867 called.
Georg Brandl014197c2008-04-09 18:40:51 +0000868
Georg Brandl2932d932008-05-30 06:27:09 +0000869 Example usage::
870
871 import io
872
873 output = io.StringIO()
874 output.write('First line.\n')
875 print('Second line.', file=output)
876
877 # Retrieve file contents -- this will be
878 # 'First line.\nSecond line.\n'
879 contents = output.getvalue()
880
Georg Brandl48310cd2009-01-03 21:18:54 +0000881 # Close object and discard memory buffer --
Georg Brandl2932d932008-05-30 06:27:09 +0000882 # .getvalue() will now raise an exception.
883 output.close()
Georg Brandl014197c2008-04-09 18:40:51 +0000884
Antoine Pitroub530e142010-08-30 12:41:00 +0000885
R David Murray1b00f252012-08-15 10:43:58 -0400886.. index::
887 single: universal newlines; io.IncrementalNewlineDecoder class
888
Georg Brandl014197c2008-04-09 18:40:51 +0000889.. class:: IncrementalNewlineDecoder
890
R David Murray1b00f252012-08-15 10:43:58 -0400891 A helper codec that decodes newlines for :term:`universal newlines` mode.
892 It inherits :class:`codecs.IncrementalDecoder`.
Georg Brandl014197c2008-04-09 18:40:51 +0000893
Antoine Pitroubed81c82010-12-03 19:14:17 +0000894
Antoine Pitroubed81c82010-12-03 19:14:17 +0000895Performance
Benjamin Petersonedf51322011-02-24 03:03:46 +0000896-----------
897
898This section discusses the performance of the provided concrete I/O
899implementations.
Antoine Pitroubed81c82010-12-03 19:14:17 +0000900
901Binary I/O
Benjamin Petersonedf51322011-02-24 03:03:46 +0000902^^^^^^^^^^
Antoine Pitroubed81c82010-12-03 19:14:17 +0000903
Benjamin Petersonedf51322011-02-24 03:03:46 +0000904By reading and writing only large chunks of data even when the user asks for a
905single byte, buffered I/O hides any inefficiency in calling and executing the
906operating system's unbuffered I/O routines. The gain depends on the OS and the
907kind of I/O which is performed. For example, on some modern OSes such as Linux,
908unbuffered disk I/O can be as fast as buffered I/O. The bottom line, however,
909is that buffered I/O offers predictable performance regardless of the platform
Eli Benderskyf877a7c2012-07-14 21:22:25 +0300910and the backing device. Therefore, it is almost always preferable to use
911buffered I/O rather than unbuffered I/O for binary data.
Antoine Pitroubed81c82010-12-03 19:14:17 +0000912
913Text I/O
Benjamin Petersonedf51322011-02-24 03:03:46 +0000914^^^^^^^^
Antoine Pitroubed81c82010-12-03 19:14:17 +0000915
916Text I/O over a binary storage (such as a file) is significantly slower than
Benjamin Petersonedf51322011-02-24 03:03:46 +0000917binary I/O over the same storage, because it requires conversions between
918unicode and binary data using a character codec. This can become noticeable
919handling huge amounts of text data like large log files. Also,
920:meth:`TextIOWrapper.tell` and :meth:`TextIOWrapper.seek` are both quite slow
921due to the reconstruction algorithm used.
Antoine Pitroubed81c82010-12-03 19:14:17 +0000922
923:class:`StringIO`, however, is a native in-memory unicode container and will
924exhibit similar speed to :class:`BytesIO`.
925
926Multi-threading
927^^^^^^^^^^^^^^^
928
Benjamin Petersonedf51322011-02-24 03:03:46 +0000929:class:`FileIO` objects are thread-safe to the extent that the operating system
930calls (such as ``read(2)`` under Unix) they wrap are thread-safe too.
Antoine Pitroubed81c82010-12-03 19:14:17 +0000931
932Binary buffered objects (instances of :class:`BufferedReader`,
933:class:`BufferedWriter`, :class:`BufferedRandom` and :class:`BufferedRWPair`)
934protect their internal structures using a lock; it is therefore safe to call
935them from multiple threads at once.
936
937:class:`TextIOWrapper` objects are not thread-safe.
938
939Reentrancy
940^^^^^^^^^^
941
942Binary buffered objects (instances of :class:`BufferedReader`,
943:class:`BufferedWriter`, :class:`BufferedRandom` and :class:`BufferedRWPair`)
944are not reentrant. While reentrant calls will not happen in normal situations,
Benjamin Petersonedf51322011-02-24 03:03:46 +0000945they can arise from doing I/O in a :mod:`signal` handler. If a thread tries to
Eli Benderskyf877a7c2012-07-14 21:22:25 +0300946re-enter a buffered object which it is already accessing, a :exc:`RuntimeError`
947is raised. Note this doesn't prohibit a different thread from entering the
Benjamin Petersonedf51322011-02-24 03:03:46 +0000948buffered object.
Antoine Pitroubed81c82010-12-03 19:14:17 +0000949
Benjamin Petersonedf51322011-02-24 03:03:46 +0000950The above implicitly extends to text files, since the :func:`open()` function
951will wrap a buffered object inside a :class:`TextIOWrapper`. This includes
952standard streams and therefore affects the built-in function :func:`print()` as
953well.
Antoine Pitroubed81c82010-12-03 19:14:17 +0000954