blob: dd98a4677ee8140aa782d3b49b2c243d6a781f69 [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
Benjamin Peterson6b4fa772010-08-30 13:19:53 +000019The :mod:`io` module provides Python's main facilities for dealing for various
20types of I/O. There are three main types of I/O: *text I/O*, *binary I/O*, *raw
21I/O*. These are generic categories, and various backing stores can be used for
22each of them. Concrete objects belonging to any of these categories will often
23be called *streams*; another common term is *file-like objects*.
Georg Brandl014197c2008-04-09 18:40:51 +000024
Antoine Pitroub530e142010-08-30 12:41:00 +000025Independently of its category, each concrete stream object will also have
Benjamin Peterson6b4fa772010-08-30 13:19:53 +000026various capabilities: it can be read-only, write-only, or read-write. It can
27also allow arbitrary random access (seeking forwards or backwards to any
28location), or only sequential access (for example in the case of a socket or
29pipe).
Georg Brandl014197c2008-04-09 18:40:51 +000030
Antoine Pitroub530e142010-08-30 12:41:00 +000031All streams are careful about the type of data you give to them. For example
32giving a :class:`str` object to the ``write()`` method of a binary stream
33will raise a ``TypeError``. So will giving a :class:`bytes` object to the
34``write()`` method of a text stream.
Georg Brandl014197c2008-04-09 18:40:51 +000035
Antoine Pitroua787b652011-10-12 19:02:52 +020036.. versionchanged:: 3.3
37 Operations defined in this module used to raise :exc:`IOError`, which is
38 now an alias of :exc:`OSError`.
39
Benjamin Peterson6b4fa772010-08-30 13:19:53 +000040
Antoine Pitroub530e142010-08-30 12:41:00 +000041Text I/O
42^^^^^^^^
Georg Brandl014197c2008-04-09 18:40:51 +000043
Benjamin Peterson6b4fa772010-08-30 13:19:53 +000044Text I/O expects and produces :class:`str` objects. This means that whenever
45the backing store is natively made of bytes (such as in the case of a file),
46encoding and decoding of data is made transparently as well as optional
47translation of platform-specific newline characters.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +000048
Benjamin Peterson6b4fa772010-08-30 13:19:53 +000049The easiest way to create a text stream is with :meth:`open()`, optionally
50specifying an encoding::
Antoine Pitroub530e142010-08-30 12:41:00 +000051
52 f = open("myfile.txt", "r", encoding="utf-8")
53
54In-memory text streams are also available as :class:`StringIO` objects::
55
56 f = io.StringIO("some initial text data")
57
Benjamin Peterson6b4fa772010-08-30 13:19:53 +000058The text stream API is described in detail in the documentation for the
59:class:`TextIOBase`.
Antoine Pitroub530e142010-08-30 12:41:00 +000060
Antoine Pitroub530e142010-08-30 12:41:00 +000061
62Binary I/O
63^^^^^^^^^^
64
Benjamin Peterson6b4fa772010-08-30 13:19:53 +000065Binary I/O (also called *buffered I/O*) expects and produces :class:`bytes`
66objects. No encoding, decoding, or newline translation is performed. This
67category of streams can be used for all kinds of non-text data, and also when
68manual control over the handling of text data is desired.
Antoine Pitroub530e142010-08-30 12:41:00 +000069
Benjamin Peterson6b4fa772010-08-30 13:19:53 +000070The easiest way to create a binary stream is with :meth:`open()` with ``'b'`` in
71the mode string::
Antoine Pitroub530e142010-08-30 12:41:00 +000072
73 f = open("myfile.jpg", "rb")
74
75In-memory binary streams are also available as :class:`BytesIO` objects::
76
77 f = io.BytesIO(b"some initial binary data: \x00\x01")
78
Benjamin Peterson6b4fa772010-08-30 13:19:53 +000079The binary stream API is described in detail in the docs of
80:class:`BufferedIOBase`.
Antoine Pitroub530e142010-08-30 12:41:00 +000081
82Other library modules may provide additional ways to create text or binary
Benjamin Peterson6b4fa772010-08-30 13:19:53 +000083streams. See :meth:`socket.socket.makefile` for example.
84
Antoine Pitroub530e142010-08-30 12:41:00 +000085
86Raw I/O
87^^^^^^^
88
89Raw I/O (also called *unbuffered I/O*) is generally used as a low-level
90building-block for binary and text streams; it is rarely useful to directly
Benjamin Peterson6b4fa772010-08-30 13:19:53 +000091manipulate a raw stream from user code. Nevertheless, you can create a raw
92stream by opening a file in binary mode with buffering disabled::
Antoine Pitroub530e142010-08-30 12:41:00 +000093
94 f = open("myfile.jpg", "rb", buffering=0)
95
Benjamin Peterson6b4fa772010-08-30 13:19:53 +000096The raw stream API is described in detail in the docs of :class:`RawIOBase`.
Benjamin Petersoncc12e1b2010-02-19 00:58:13 +000097
Georg Brandl014197c2008-04-09 18:40:51 +000098
Antoine Pitroub530e142010-08-30 12:41:00 +000099High-level Module Interface
100---------------------------
Georg Brandl014197c2008-04-09 18:40:51 +0000101
102.. data:: DEFAULT_BUFFER_SIZE
103
104 An int containing the default buffer size used by the module's buffered I/O
Benjamin Peterson6b4fa772010-08-30 13:19:53 +0000105 classes. :func:`open` uses the file's blksize (as obtained by
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000106 :func:`os.stat`) if possible.
Georg Brandl014197c2008-04-09 18:40:51 +0000107
Benjamin Peterson6b4fa772010-08-30 13:19:53 +0000108
Benjamin Peterson95e392c2010-04-27 21:07:21 +0000109.. function:: open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True)
Georg Brandl014197c2008-04-09 18:40:51 +0000110
Benjamin Peterson6b4fa772010-08-30 13:19:53 +0000111 This is an alias for the builtin :func:`open` function.
Georg Brandl014197c2008-04-09 18:40:51 +0000112
Georg Brandl014197c2008-04-09 18:40:51 +0000113
114.. exception:: BlockingIOError
115
Antoine Pitrouf55011f2011-10-12 18:57:23 +0200116 This is a compatibility alias for the builtin :exc:`BlockingIOError`
117 exception.
Georg Brandl014197c2008-04-09 18:40:51 +0000118
119
120.. exception:: UnsupportedOperation
121
Antoine Pitroua787b652011-10-12 19:02:52 +0200122 An exception inheriting :exc:`OSError` and :exc:`ValueError` that is raised
Georg Brandl014197c2008-04-09 18:40:51 +0000123 when an unsupported operation is called on a stream.
124
125
Antoine Pitroub530e142010-08-30 12:41:00 +0000126In-memory streams
127^^^^^^^^^^^^^^^^^
128
129It is also possible to use a :class:`str` or :class:`bytes`-like object as a
Benjamin Peterson6b4fa772010-08-30 13:19:53 +0000130file for both reading and writing. For strings :class:`StringIO` can be used
131like a file opened in text mode. :class:`BytesIO` can be used like a file
132opened in binary mode. Both provide full read-write capabilities with random
133access.
Antoine Pitroub530e142010-08-30 12:41:00 +0000134
135
136.. seealso::
Benjamin Peterson6b4fa772010-08-30 13:19:53 +0000137
Antoine Pitroub530e142010-08-30 12:41:00 +0000138 :mod:`sys`
139 contains the standard IO streams: :data:`sys.stdin`, :data:`sys.stdout`,
140 and :data:`sys.stderr`.
141
142
143Class hierarchy
144---------------
145
Benjamin Peterson6b4fa772010-08-30 13:19:53 +0000146The implementation of I/O streams is organized as a hierarchy of classes. First
147:term:`abstract base classes <abstract base class>` (ABCs), which are used to
148specify the various categories of streams, then concrete classes providing the
149standard stream implementations.
Antoine Pitroub530e142010-08-30 12:41:00 +0000150
151 .. note::
Benjamin Peterson6b4fa772010-08-30 13:19:53 +0000152
153 The abstract base classes also provide default implementations of some
154 methods in order to help implementation of concrete stream classes. For
155 example, :class:`BufferedIOBase` provides unoptimized implementations of
156 ``readinto()`` and ``readline()``.
Antoine Pitroub530e142010-08-30 12:41:00 +0000157
158At the top of the I/O hierarchy is the abstract base class :class:`IOBase`. It
159defines the basic interface to a stream. Note, however, that there is no
160separation between reading and writing to streams; implementations are allowed
Benjamin Peterson6b4fa772010-08-30 13:19:53 +0000161to raise :exc:`UnsupportedOperation` if they do not support a given operation.
Antoine Pitroub530e142010-08-30 12:41:00 +0000162
Benjamin Peterson6b4fa772010-08-30 13:19:53 +0000163The :class:`RawIOBase` ABC extends :class:`IOBase`. It deals with the reading
164and writing of bytes to a stream. :class:`FileIO` subclasses :class:`RawIOBase`
165to provide an interface to files in the machine's file system.
Antoine Pitroub530e142010-08-30 12:41:00 +0000166
167The :class:`BufferedIOBase` ABC deals with buffering on a raw byte stream
168(:class:`RawIOBase`). Its subclasses, :class:`BufferedWriter`,
169:class:`BufferedReader`, and :class:`BufferedRWPair` buffer streams that are
Benjamin Peterson6b4fa772010-08-30 13:19:53 +0000170readable, writable, and both readable and writable. :class:`BufferedRandom`
171provides a buffered interface to random access streams. Another
Georg Brandl682d7e02010-10-06 10:26:05 +0000172:class:`BufferedIOBase` subclass, :class:`BytesIO`, is a stream of in-memory
Benjamin Peterson6b4fa772010-08-30 13:19:53 +0000173bytes.
Antoine Pitroub530e142010-08-30 12:41:00 +0000174
Benjamin Peterson6b4fa772010-08-30 13:19:53 +0000175The :class:`TextIOBase` ABC, another subclass of :class:`IOBase`, deals with
176streams whose bytes represent text, and handles encoding and decoding to and
177from strings. :class:`TextIOWrapper`, which extends it, is a buffered text
178interface to a buffered raw stream (:class:`BufferedIOBase`). Finally,
179:class:`StringIO` is an in-memory stream for text.
Antoine Pitroub530e142010-08-30 12:41:00 +0000180
181Argument names are not part of the specification, and only the arguments of
Benjamin Peterson6b4fa772010-08-30 13:19:53 +0000182:func:`open` are intended to be used as keyword arguments.
Antoine Pitroub530e142010-08-30 12:41:00 +0000183
184
Georg Brandl014197c2008-04-09 18:40:51 +0000185I/O Base Classes
Antoine Pitroub530e142010-08-30 12:41:00 +0000186^^^^^^^^^^^^^^^^
Georg Brandl014197c2008-04-09 18:40:51 +0000187
188.. class:: IOBase
189
190 The abstract base class for all I/O classes, acting on streams of bytes.
191 There is no public constructor.
192
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000193 This class provides empty abstract implementations for many methods
194 that derived classes can override selectively; the default
195 implementations represent a file that cannot be read, written or
196 seeked.
Georg Brandl014197c2008-04-09 18:40:51 +0000197
198 Even though :class:`IOBase` does not declare :meth:`read`, :meth:`readinto`,
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000199 or :meth:`write` because their signatures will vary, implementations and
200 clients should consider those methods part of the interface. Also,
Antoine Pitroua787b652011-10-12 19:02:52 +0200201 implementations may raise a :exc:`ValueError` (or :exc:`UnsupportedOperation`)
202 when operations they do not support are called.
Georg Brandl014197c2008-04-09 18:40:51 +0000203
204 The basic type used for binary data read from or written to a file is
205 :class:`bytes`. :class:`bytearray`\s are accepted too, and in some cases
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000206 (such as :class:`readinto`) required. Text I/O classes work with
207 :class:`str` data.
Georg Brandl014197c2008-04-09 18:40:51 +0000208
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000209 Note that calling any method (even inquiries) on a closed stream is
Antoine Pitroua787b652011-10-12 19:02:52 +0200210 undefined. Implementations may raise :exc:`ValueError` in this case.
Georg Brandl014197c2008-04-09 18:40:51 +0000211
212 IOBase (and its subclasses) support the iterator protocol, meaning that an
213 :class:`IOBase` object can be iterated over yielding the lines in a stream.
Antoine Pitrou497a7672009-09-17 17:18:01 +0000214 Lines are defined slightly differently depending on whether the stream is
215 a binary stream (yielding bytes), or a text stream (yielding character
Meador Inge777bebb2011-12-03 12:29:54 -0600216 strings). See :meth:`~IOBase.readline` below.
Georg Brandl014197c2008-04-09 18:40:51 +0000217
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000218 IOBase is also a context manager and therefore supports the
219 :keyword:`with` statement. In this example, *file* is closed after the
220 :keyword:`with` statement's suite is finished---even if an exception occurs::
Georg Brandl014197c2008-04-09 18:40:51 +0000221
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000222 with open('spam.txt', 'w') as file:
223 file.write('Spam and eggs!')
Georg Brandl014197c2008-04-09 18:40:51 +0000224
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000225 :class:`IOBase` provides these data attributes and methods:
Georg Brandl014197c2008-04-09 18:40:51 +0000226
227 .. method:: close()
228
Christian Heimesecc42a22008-11-05 19:30:32 +0000229 Flush and close this stream. This method has no effect if the file is
Georg Brandl48310cd2009-01-03 21:18:54 +0000230 already closed. Once the file is closed, any operation on the file
Georg Brandl8569e582010-05-19 20:57:08 +0000231 (e.g. reading or writing) will raise a :exc:`ValueError`.
Antoine Pitrouf9fc08f2010-04-28 19:59:32 +0000232
233 As a convenience, it is allowed to call this method more than once;
234 only the first call, however, will have an effect.
Georg Brandl014197c2008-04-09 18:40:51 +0000235
236 .. attribute:: closed
237
238 True if the stream is closed.
239
240 .. method:: fileno()
241
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000242 Return the underlying file descriptor (an integer) of the stream if it
Antoine Pitroua787b652011-10-12 19:02:52 +0200243 exists. An :exc:`OSError` is raised if the IO object does not use a file
Georg Brandl014197c2008-04-09 18:40:51 +0000244 descriptor.
245
246 .. method:: flush()
247
Benjamin Petersonb85a5842008-04-13 21:39:58 +0000248 Flush the write buffers of the stream if applicable. This does nothing
249 for read-only and non-blocking streams.
Georg Brandl014197c2008-04-09 18:40:51 +0000250
251 .. method:: isatty()
252
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000253 Return ``True`` if the stream is interactive (i.e., connected to
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000254 a terminal/tty device).
Georg Brandl014197c2008-04-09 18:40:51 +0000255
256 .. method:: readable()
257
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000258 Return ``True`` if the stream can be read from. If False, :meth:`read`
Antoine Pitroua787b652011-10-12 19:02:52 +0200259 will raise :exc:`OSError`.
Georg Brandl014197c2008-04-09 18:40:51 +0000260
Georg Brandl3dd33882009-06-01 17:35:27 +0000261 .. method:: readline(limit=-1)
Georg Brandl014197c2008-04-09 18:40:51 +0000262
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000263 Read and return one line from the stream. If *limit* is specified, at
264 most *limit* bytes will be read.
Georg Brandl014197c2008-04-09 18:40:51 +0000265
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000266 The line terminator is always ``b'\n'`` for binary files; for text files,
Benjamin Peterson6b4fa772010-08-30 13:19:53 +0000267 the *newlines* argument to :func:`open` can be used to select the line
Georg Brandl014197c2008-04-09 18:40:51 +0000268 terminator(s) recognized.
269
Georg Brandl3dd33882009-06-01 17:35:27 +0000270 .. method:: readlines(hint=-1)
Georg Brandl014197c2008-04-09 18:40:51 +0000271
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000272 Read and return a list of lines from the stream. *hint* can be specified
273 to control the number of lines read: no more lines will be read if the
274 total size (in bytes/characters) of all lines so far exceeds *hint*.
Georg Brandl014197c2008-04-09 18:40:51 +0000275
Georg Brandl3dd33882009-06-01 17:35:27 +0000276 .. method:: seek(offset, whence=SEEK_SET)
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000277
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000278 Change the stream position to the given byte *offset*. *offset* is
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000279 interpreted relative to the position indicated by *whence*. Values for
280 *whence* are:
281
Benjamin Peterson0e4caf42009-04-01 21:22:20 +0000282 * :data:`SEEK_SET` or ``0`` -- start of the stream (the default);
283 *offset* should be zero or positive
284 * :data:`SEEK_CUR` or ``1`` -- current stream position; *offset* may
285 be negative
286 * :data:`SEEK_END` or ``2`` -- end of the stream; *offset* is usually
287 negative
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000288
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000289 Return the new absolute position.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000290
Raymond Hettinger35a88362009-04-09 00:08:24 +0000291 .. versionadded:: 3.1
Georg Brandl67b21b72010-08-17 15:07:14 +0000292 The ``SEEK_*`` constants.
Benjamin Peterson0e4caf42009-04-01 21:22:20 +0000293
Jesus Cea94363612012-06-22 18:32:07 +0200294 .. versionadded:: 3.3
295 Some operating systems could support additional values, like
296 :data:`os.SEEK_HOLE` or :data:`os.SEEK_DATA`. The valid values
297 for a file could depend on it being open in text or binary mode.
298
Georg Brandl014197c2008-04-09 18:40:51 +0000299 .. method:: seekable()
300
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000301 Return ``True`` if the stream supports random access. If ``False``,
Antoine Pitroua787b652011-10-12 19:02:52 +0200302 :meth:`seek`, :meth:`tell` and :meth:`truncate` will raise :exc:`OSError`.
Georg Brandl014197c2008-04-09 18:40:51 +0000303
304 .. method:: tell()
305
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000306 Return the current stream position.
Georg Brandl014197c2008-04-09 18:40:51 +0000307
Georg Brandl3dd33882009-06-01 17:35:27 +0000308 .. method:: truncate(size=None)
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000309
Antoine Pitrou2016dc92010-05-29 12:08:25 +0000310 Resize the stream to the given *size* in bytes (or the current position
311 if *size* is not specified). The current stream position isn't changed.
312 This resizing can extend or reduce the current file size. In case of
313 extension, the contents of the new file area depend on the platform
314 (on most systems, additional bytes are zero-filled, on Windows they're
315 undetermined). The new file size is returned.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000316
Georg Brandl014197c2008-04-09 18:40:51 +0000317 .. method:: writable()
318
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000319 Return ``True`` if the stream supports writing. If ``False``,
Antoine Pitroua787b652011-10-12 19:02:52 +0200320 :meth:`write` and :meth:`truncate` will raise :exc:`OSError`.
Georg Brandl014197c2008-04-09 18:40:51 +0000321
322 .. method:: writelines(lines)
323
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000324 Write a list of lines to the stream. Line separators are not added, so it
325 is usual for each of the lines provided to have a line separator at the
326 end.
Georg Brandl014197c2008-04-09 18:40:51 +0000327
328
329.. class:: RawIOBase
330
331 Base class for raw binary I/O. It inherits :class:`IOBase`. There is no
332 public constructor.
333
Antoine Pitrou497a7672009-09-17 17:18:01 +0000334 Raw binary I/O typically provides low-level access to an underlying OS
335 device or API, and does not try to encapsulate it in high-level primitives
336 (this is left to Buffered I/O and Text I/O, described later in this page).
337
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000338 In addition to the attributes and methods from :class:`IOBase`,
339 RawIOBase provides the following methods:
Georg Brandl014197c2008-04-09 18:40:51 +0000340
Georg Brandl3dd33882009-06-01 17:35:27 +0000341 .. method:: read(n=-1)
Georg Brandl014197c2008-04-09 18:40:51 +0000342
Antoine Pitrou78ddbe62009-10-01 16:24:45 +0000343 Read up to *n* bytes from the object and return them. As a convenience,
344 if *n* is unspecified or -1, :meth:`readall` is called. Otherwise,
345 only one system call is ever made. Fewer than *n* bytes may be
346 returned if the operating system call returns fewer than *n* bytes.
347
348 If 0 bytes are returned, and *n* was not 0, this indicates end of file.
349 If the object is in non-blocking mode and no bytes are available,
350 ``None`` is returned.
Georg Brandl014197c2008-04-09 18:40:51 +0000351
Benjamin Petersonb47aace2008-04-09 21:38:38 +0000352 .. method:: readall()
Georg Brandl014197c2008-04-09 18:40:51 +0000353
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000354 Read and return all the bytes from the stream until EOF, using multiple
355 calls to the stream if necessary.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000356
357 .. method:: readinto(b)
358
Daniel Stutzbachd01df462010-11-30 17:49:53 +0000359 Read up to len(b) bytes into bytearray *b* and return the number
360 of bytes read. If the object is in non-blocking mode and no
361 bytes are available, ``None`` is returned.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000362
363 .. method:: write(b)
364
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000365 Write the given bytes or bytearray object, *b*, to the underlying raw
Antoine Pitrou497a7672009-09-17 17:18:01 +0000366 stream and return the number of bytes written. This can be less than
367 ``len(b)``, depending on specifics of the underlying raw stream, and
368 especially if it is in non-blocking mode. ``None`` is returned if the
369 raw stream is set not to block and no single byte could be readily
370 written to it.
Georg Brandl014197c2008-04-09 18:40:51 +0000371
372
Georg Brandl014197c2008-04-09 18:40:51 +0000373.. class:: BufferedIOBase
374
Antoine Pitrou497a7672009-09-17 17:18:01 +0000375 Base class for binary streams that support some kind of buffering.
376 It inherits :class:`IOBase`. There is no public constructor.
Georg Brandl014197c2008-04-09 18:40:51 +0000377
Antoine Pitrou497a7672009-09-17 17:18:01 +0000378 The main difference with :class:`RawIOBase` is that methods :meth:`read`,
379 :meth:`readinto` and :meth:`write` will try (respectively) to read as much
380 input as requested or to consume all given output, at the expense of
381 making perhaps more than one system call.
382
383 In addition, those methods can raise :exc:`BlockingIOError` if the
384 underlying raw stream is in non-blocking mode and cannot take or give
385 enough data; unlike their :class:`RawIOBase` counterparts, they will
386 never return ``None``.
387
388 Besides, the :meth:`read` method does not have a default
Georg Brandl014197c2008-04-09 18:40:51 +0000389 implementation that defers to :meth:`readinto`.
390
Antoine Pitrou497a7672009-09-17 17:18:01 +0000391 A typical :class:`BufferedIOBase` implementation should not inherit from a
392 :class:`RawIOBase` implementation, but wrap one, like
393 :class:`BufferedWriter` and :class:`BufferedReader` do.
Georg Brandl014197c2008-04-09 18:40:51 +0000394
Senthil Kumarana6bac952011-07-04 11:28:30 -0700395 :class:`BufferedIOBase` provides or overrides these methods and attribute in
396 addition to those from :class:`IOBase`:
Georg Brandl014197c2008-04-09 18:40:51 +0000397
Benjamin Petersonc609b6b2009-06-28 17:32:20 +0000398 .. attribute:: raw
399
400 The underlying raw stream (a :class:`RawIOBase` instance) that
401 :class:`BufferedIOBase` deals with. This is not part of the
402 :class:`BufferedIOBase` API and may not exist on some implementations.
403
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000404 .. method:: detach()
405
406 Separate the underlying raw stream from the buffer and return it.
407
408 After the raw stream has been detached, the buffer is in an unusable
409 state.
410
411 Some buffers, like :class:`BytesIO`, do not have the concept of a single
412 raw stream to return from this method. They raise
413 :exc:`UnsupportedOperation`.
414
Benjamin Petersonedc36472009-05-01 20:48:14 +0000415 .. versionadded:: 3.1
416
Georg Brandl3dd33882009-06-01 17:35:27 +0000417 .. method:: read(n=-1)
Georg Brandl014197c2008-04-09 18:40:51 +0000418
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000419 Read and return up to *n* bytes. If the argument is omitted, ``None``, or
Georg Brandl014197c2008-04-09 18:40:51 +0000420 negative, data is read and returned until EOF is reached. An empty bytes
421 object is returned if the stream is already at EOF.
422
423 If the argument is positive, and the underlying raw stream is not
424 interactive, multiple raw reads may be issued to satisfy the byte count
425 (unless EOF is reached first). But for interactive raw streams, at most
426 one raw read will be issued, and a short result does not imply that EOF is
427 imminent.
428
Antoine Pitrou497a7672009-09-17 17:18:01 +0000429 A :exc:`BlockingIOError` is raised if the underlying raw stream is in
430 non blocking-mode, and has no data available at the moment.
Georg Brandl014197c2008-04-09 18:40:51 +0000431
Georg Brandl3dd33882009-06-01 17:35:27 +0000432 .. method:: read1(n=-1)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000433
434 Read and return up to *n* bytes, with at most one call to the underlying
Antoine Pitrou497a7672009-09-17 17:18:01 +0000435 raw stream's :meth:`~RawIOBase.read` method. This can be useful if you
436 are implementing your own buffering on top of a :class:`BufferedIOBase`
437 object.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000438
Georg Brandl014197c2008-04-09 18:40:51 +0000439 .. method:: readinto(b)
440
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000441 Read up to len(b) bytes into bytearray *b* and return the number of bytes
Georg Brandl014197c2008-04-09 18:40:51 +0000442 read.
443
444 Like :meth:`read`, multiple reads may be issued to the underlying raw
Antoine Pitrou497a7672009-09-17 17:18:01 +0000445 stream, unless the latter is 'interactive'.
Georg Brandl014197c2008-04-09 18:40:51 +0000446
Antoine Pitrou497a7672009-09-17 17:18:01 +0000447 A :exc:`BlockingIOError` is raised if the underlying raw stream is in
448 non blocking-mode, and has no data available at the moment.
Georg Brandl014197c2008-04-09 18:40:51 +0000449
Georg Brandl014197c2008-04-09 18:40:51 +0000450 .. method:: write(b)
451
Antoine Pitrou497a7672009-09-17 17:18:01 +0000452 Write the given bytes or bytearray object, *b* and return the number
453 of bytes written (never less than ``len(b)``, since if the write fails
Antoine Pitroua787b652011-10-12 19:02:52 +0200454 an :exc:`OSError` will be raised). Depending on the actual
Antoine Pitrou497a7672009-09-17 17:18:01 +0000455 implementation, these bytes may be readily written to the underlying
456 stream, or held in a buffer for performance and latency reasons.
Georg Brandl014197c2008-04-09 18:40:51 +0000457
Antoine Pitrou497a7672009-09-17 17:18:01 +0000458 When in non-blocking mode, a :exc:`BlockingIOError` is raised if the
459 data needed to be written to the raw stream but it couldn't accept
460 all the data without blocking.
Georg Brandl014197c2008-04-09 18:40:51 +0000461
462
Benjamin Petersonaa069002009-01-23 03:26:36 +0000463Raw File I/O
Antoine Pitroub530e142010-08-30 12:41:00 +0000464^^^^^^^^^^^^
Benjamin Petersonaa069002009-01-23 03:26:36 +0000465
Ross Lagerwall59142db2011-10-31 20:34:46 +0200466.. class:: FileIO(name, mode='r', closefd=True, opener=None)
Benjamin Petersonaa069002009-01-23 03:26:36 +0000467
Antoine Pitrou497a7672009-09-17 17:18:01 +0000468 :class:`FileIO` represents an OS-level file containing bytes data.
469 It implements the :class:`RawIOBase` interface (and therefore the
470 :class:`IOBase` interface, too).
471
472 The *name* can be one of two things:
473
474 * a character string or bytes object representing the path to the file
475 which will be opened;
476 * an integer representing the number of an existing OS-level file descriptor
477 to which the resulting :class:`FileIO` object will give access.
Benjamin Petersonaa069002009-01-23 03:26:36 +0000478
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100479 The *mode* can be ``'r'``, ``'w'``, ``'x'`` or ``'a'`` for reading
Charles-François Natalid612de12012-01-14 11:51:00 +0100480 (default), writing, exclusive creation or appending. The file will be
481 created if it doesn't exist when opened for writing or appending; it will be
482 truncated when opened for writing. :exc:`FileExistsError` will be raised if
483 it already exists when opened for creating. Opening a file for creating
484 implies writing, so this mode behaves in a similar way to ``'w'``. Add a
485 ``'+'`` to the mode to allow simultaneous reading and writing.
Benjamin Petersonaa069002009-01-23 03:26:36 +0000486
Antoine Pitrou497a7672009-09-17 17:18:01 +0000487 The :meth:`read` (when called with a positive argument), :meth:`readinto`
488 and :meth:`write` methods on this class will only make one system call.
489
Ross Lagerwall59142db2011-10-31 20:34:46 +0200490 A custom opener can be used by passing a callable as *opener*. The underlying
491 file descriptor for the file object is then obtained by calling *opener* with
492 (*name*, *flags*). *opener* must return an open file descriptor (passing
493 :mod:`os.open` as *opener* results in functionality similar to passing
494 ``None``).
495
496 .. versionchanged:: 3.3
497 The *opener* parameter was added.
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100498 The ``'x'`` mode was added.
Ross Lagerwall59142db2011-10-31 20:34:46 +0200499
Benjamin Petersonaa069002009-01-23 03:26:36 +0000500 In addition to the attributes and methods from :class:`IOBase` and
501 :class:`RawIOBase`, :class:`FileIO` provides the following data
502 attributes and methods:
503
504 .. attribute:: mode
505
506 The mode as given in the constructor.
507
508 .. attribute:: name
509
510 The file name. This is the file descriptor of the file when no name is
511 given in the constructor.
512
Benjamin Petersonaa069002009-01-23 03:26:36 +0000513
514Buffered Streams
Antoine Pitroub530e142010-08-30 12:41:00 +0000515^^^^^^^^^^^^^^^^
Benjamin Petersonaa069002009-01-23 03:26:36 +0000516
Antoine Pitroubed81c82010-12-03 19:14:17 +0000517Buffered I/O streams provide a higher-level interface to an I/O device
518than raw I/O does.
Antoine Pitrou497a7672009-09-17 17:18:01 +0000519
Georg Brandl014197c2008-04-09 18:40:51 +0000520.. class:: BytesIO([initial_bytes])
521
522 A stream implementation using an in-memory bytes buffer. It inherits
523 :class:`BufferedIOBase`.
524
Antoine Pitroub530e142010-08-30 12:41:00 +0000525 The argument *initial_bytes* contains optional initial :class:`bytes` data.
Georg Brandl014197c2008-04-09 18:40:51 +0000526
527 :class:`BytesIO` provides or overrides these methods in addition to those
528 from :class:`BufferedIOBase` and :class:`IOBase`:
529
Antoine Pitrou972ee132010-09-06 18:48:21 +0000530 .. method:: getbuffer()
531
532 Return a readable and writable view over the contents of the buffer
533 without copying them. Also, mutating the view will transparently
534 update the contents of the buffer::
535
536 >>> b = io.BytesIO(b"abcdef")
537 >>> view = b.getbuffer()
538 >>> view[2:4] = b"56"
539 >>> b.getvalue()
540 b'ab56ef'
541
542 .. note::
543 As long as the view exists, the :class:`BytesIO` object cannot be
544 resized.
545
546 .. versionadded:: 3.2
547
Georg Brandl014197c2008-04-09 18:40:51 +0000548 .. method:: getvalue()
549
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000550 Return ``bytes`` containing the entire contents of the buffer.
Georg Brandl014197c2008-04-09 18:40:51 +0000551
552 .. method:: read1()
553
Benjamin Peterson9efcc4b2008-04-14 21:30:21 +0000554 In :class:`BytesIO`, this is the same as :meth:`read`.
Georg Brandl014197c2008-04-09 18:40:51 +0000555
Georg Brandl014197c2008-04-09 18:40:51 +0000556
Georg Brandl3dd33882009-06-01 17:35:27 +0000557.. class:: BufferedReader(raw, buffer_size=DEFAULT_BUFFER_SIZE)
Georg Brandl014197c2008-04-09 18:40:51 +0000558
Antoine Pitrou497a7672009-09-17 17:18:01 +0000559 A buffer providing higher-level access to a readable, sequential
560 :class:`RawIOBase` object. It inherits :class:`BufferedIOBase`.
561 When reading data from this object, a larger amount of data may be
562 requested from the underlying raw stream, and kept in an internal buffer.
563 The buffered data can then be returned directly on subsequent reads.
Georg Brandl014197c2008-04-09 18:40:51 +0000564
565 The constructor creates a :class:`BufferedReader` for the given readable
566 *raw* stream and *buffer_size*. If *buffer_size* is omitted,
567 :data:`DEFAULT_BUFFER_SIZE` is used.
568
569 :class:`BufferedReader` provides or overrides these methods in addition to
570 those from :class:`BufferedIOBase` and :class:`IOBase`:
571
572 .. method:: peek([n])
573
Benjamin Petersonc43a26d2009-06-16 23:09:24 +0000574 Return bytes from the stream without advancing the position. At most one
Benjamin Peterson2a8b54d2009-06-14 14:37:23 +0000575 single read on the raw stream is done to satisfy the call. The number of
576 bytes returned may be less or more than requested.
Georg Brandl014197c2008-04-09 18:40:51 +0000577
578 .. method:: read([n])
579
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000580 Read and return *n* bytes, or if *n* is not given or negative, until EOF
Georg Brandl014197c2008-04-09 18:40:51 +0000581 or if the read call would block in non-blocking mode.
582
583 .. method:: read1(n)
584
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000585 Read and return up to *n* bytes with only one call on the raw stream. If
Georg Brandl014197c2008-04-09 18:40:51 +0000586 at least one byte is buffered, only buffered bytes are returned.
587 Otherwise, one raw stream read call is made.
588
589
Georg Brandl3dd33882009-06-01 17:35:27 +0000590.. class:: BufferedWriter(raw, buffer_size=DEFAULT_BUFFER_SIZE)
Georg Brandl014197c2008-04-09 18:40:51 +0000591
Antoine Pitrou497a7672009-09-17 17:18:01 +0000592 A buffer providing higher-level access to a writeable, sequential
593 :class:`RawIOBase` object. It inherits :class:`BufferedIOBase`.
594 When writing to this object, data is normally held into an internal
595 buffer. The buffer will be written out to the underlying :class:`RawIOBase`
596 object under various conditions, including:
597
598 * when the buffer gets too small for all pending data;
599 * when :meth:`flush()` is called;
600 * when a :meth:`seek()` is requested (for :class:`BufferedRandom` objects);
601 * when the :class:`BufferedWriter` object is closed or destroyed.
Georg Brandl014197c2008-04-09 18:40:51 +0000602
603 The constructor creates a :class:`BufferedWriter` for the given writeable
604 *raw* stream. If the *buffer_size* is not given, it defaults to
Benjamin Peterson394ee002009-03-05 22:33:59 +0000605 :data:`DEFAULT_BUFFER_SIZE`.
606
Georg Brandl014197c2008-04-09 18:40:51 +0000607 :class:`BufferedWriter` provides or overrides these methods in addition to
608 those from :class:`BufferedIOBase` and :class:`IOBase`:
609
610 .. method:: flush()
611
612 Force bytes held in the buffer into the raw stream. A
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000613 :exc:`BlockingIOError` should be raised if the raw stream blocks.
Georg Brandl014197c2008-04-09 18:40:51 +0000614
615 .. method:: write(b)
616
Antoine Pitrou497a7672009-09-17 17:18:01 +0000617 Write the bytes or bytearray object, *b* and return the number of bytes
618 written. When in non-blocking mode, a :exc:`BlockingIOError` is raised
619 if the buffer needs to be written out but the raw stream blocks.
Georg Brandl014197c2008-04-09 18:40:51 +0000620
621
Georg Brandl3dd33882009-06-01 17:35:27 +0000622.. class:: BufferedRandom(raw, buffer_size=DEFAULT_BUFFER_SIZE)
Georg Brandl014197c2008-04-09 18:40:51 +0000623
624 A buffered interface to random access streams. It inherits
Antoine Pitrou497a7672009-09-17 17:18:01 +0000625 :class:`BufferedReader` and :class:`BufferedWriter`, and further supports
626 :meth:`seek` and :meth:`tell` functionality.
Georg Brandl014197c2008-04-09 18:40:51 +0000627
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000628 The constructor creates a reader and writer for a seekable raw stream, given
Georg Brandl014197c2008-04-09 18:40:51 +0000629 in the first argument. If the *buffer_size* is omitted it defaults to
Benjamin Peterson394ee002009-03-05 22:33:59 +0000630 :data:`DEFAULT_BUFFER_SIZE`.
631
Georg Brandl014197c2008-04-09 18:40:51 +0000632 :class:`BufferedRandom` is capable of anything :class:`BufferedReader` or
633 :class:`BufferedWriter` can do.
634
635
Antoine Pitrou13d28952011-08-20 19:48:43 +0200636.. class:: BufferedRWPair(reader, writer, buffer_size=DEFAULT_BUFFER_SIZE)
637
638 A buffered I/O object combining two unidirectional :class:`RawIOBase`
639 objects -- one readable, the other writeable -- into a single bidirectional
640 endpoint. It inherits :class:`BufferedIOBase`.
641
642 *reader* and *writer* are :class:`RawIOBase` objects that are readable and
643 writeable respectively. If the *buffer_size* is omitted it defaults to
644 :data:`DEFAULT_BUFFER_SIZE`.
645
Antoine Pitrou13d28952011-08-20 19:48:43 +0200646 :class:`BufferedRWPair` implements all of :class:`BufferedIOBase`\'s methods
647 except for :meth:`~BufferedIOBase.detach`, which raises
648 :exc:`UnsupportedOperation`.
649
650 .. warning::
651 :class:`BufferedRWPair` does not attempt to synchronize accesses to
652 its underlying raw streams. You should not pass it the same object
653 as reader and writer; use :class:`BufferedRandom` instead.
654
655
Georg Brandl014197c2008-04-09 18:40:51 +0000656Text I/O
Antoine Pitroub530e142010-08-30 12:41:00 +0000657^^^^^^^^
Georg Brandl014197c2008-04-09 18:40:51 +0000658
659.. class:: TextIOBase
660
661 Base class for text streams. This class provides a character and line based
662 interface to stream I/O. There is no :meth:`readinto` method because
663 Python's character strings are immutable. It inherits :class:`IOBase`.
664 There is no public constructor.
665
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000666 :class:`TextIOBase` provides or overrides these data attributes and
667 methods in addition to those from :class:`IOBase`:
Georg Brandl014197c2008-04-09 18:40:51 +0000668
669 .. attribute:: encoding
670
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000671 The name of the encoding used to decode the stream's bytes into
Georg Brandl014197c2008-04-09 18:40:51 +0000672 strings, and to encode strings into bytes.
673
Benjamin Peterson0926ad12009-06-06 18:02:12 +0000674 .. attribute:: errors
675
676 The error setting of the decoder or encoder.
677
Georg Brandl014197c2008-04-09 18:40:51 +0000678 .. attribute:: newlines
679
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000680 A string, a tuple of strings, or ``None``, indicating the newlines
Antoine Pitrou497a7672009-09-17 17:18:01 +0000681 translated so far. Depending on the implementation and the initial
682 constructor flags, this may not be available.
Georg Brandl014197c2008-04-09 18:40:51 +0000683
Benjamin Petersonc609b6b2009-06-28 17:32:20 +0000684 .. attribute:: buffer
685
686 The underlying binary buffer (a :class:`BufferedIOBase` instance) that
687 :class:`TextIOBase` deals with. This is not part of the
688 :class:`TextIOBase` API and may not exist on some implementations.
689
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000690 .. method:: detach()
691
Antoine Pitrou497a7672009-09-17 17:18:01 +0000692 Separate the underlying binary buffer from the :class:`TextIOBase` and
693 return it.
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000694
695 After the underlying buffer has been detached, the :class:`TextIOBase` is
696 in an unusable state.
697
698 Some :class:`TextIOBase` implementations, like :class:`StringIO`, may not
699 have the concept of an underlying buffer and calling this method will
700 raise :exc:`UnsupportedOperation`.
701
Benjamin Petersonedc36472009-05-01 20:48:14 +0000702 .. versionadded:: 3.1
703
Georg Brandl014197c2008-04-09 18:40:51 +0000704 .. method:: read(n)
705
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000706 Read and return at most *n* characters from the stream as a single
Antoine Pitrou497a7672009-09-17 17:18:01 +0000707 :class:`str`. If *n* is negative or ``None``, reads until EOF.
Georg Brandl014197c2008-04-09 18:40:51 +0000708
709 .. method:: readline()
710
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000711 Read until newline or EOF and return a single ``str``. If the stream is
712 already at EOF, an empty string is returned.
Georg Brandl014197c2008-04-09 18:40:51 +0000713
Antoine Pitrouf49d1522012-01-21 20:20:49 +0100714 .. method:: seek(offset, whence=SEEK_SET)
715
716 Change the stream position to the given *offset*. Behaviour depends
717 on the *whence* parameter:
718
719 * :data:`SEEK_SET` or ``0``: seek from the start of the stream
720 (the default); *offset* must either be a number returned by
721 :meth:`TextIOBase.tell`, or zero. Any other *offset* value
722 produces undefined behaviour.
723 * :data:`SEEK_CUR` or ``1``: "seek" to the current position;
724 *offset* must be zero, which is a no-operation (all other values
725 are unsupported).
726 * :data:`SEEK_END` or ``2``: seek to the end of the stream;
727 *offset* must be zero (all other values are unsupported).
728
729 Return the new absolute position as an opaque number.
730
731 .. versionadded:: 3.1
732 The ``SEEK_*`` constants.
733
734 .. method:: tell()
735
736 Return the current stream position as an opaque number. The number
737 does not usually represent a number of bytes in the underlying
738 binary storage.
739
Georg Brandl014197c2008-04-09 18:40:51 +0000740 .. method:: write(s)
741
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000742 Write the string *s* to the stream and return the number of characters
743 written.
Georg Brandl014197c2008-04-09 18:40:51 +0000744
745
Antoine Pitrou664091b2011-07-23 22:00:03 +0200746.. class:: TextIOWrapper(buffer, encoding=None, errors=None, newline=None, \
747 line_buffering=False, write_through=False)
Georg Brandl014197c2008-04-09 18:40:51 +0000748
Antoine Pitrou497a7672009-09-17 17:18:01 +0000749 A buffered text stream over a :class:`BufferedIOBase` binary stream.
Georg Brandl014197c2008-04-09 18:40:51 +0000750 It inherits :class:`TextIOBase`.
751
752 *encoding* gives the name of the encoding that the stream will be decoded or
Victor Stinnerf86a5e82012-06-05 13:43:22 +0200753 encoded with. It defaults to ``locale.getpreferredencoding(False)``.
Georg Brandl014197c2008-04-09 18:40:51 +0000754
Benjamin Petersonb85a5842008-04-13 21:39:58 +0000755 *errors* is an optional string that specifies how encoding and decoding
756 errors are to be handled. Pass ``'strict'`` to raise a :exc:`ValueError`
757 exception if there is an encoding error (the default of ``None`` has the same
758 effect), or pass ``'ignore'`` to ignore errors. (Note that ignoring encoding
759 errors can lead to data loss.) ``'replace'`` causes a replacement marker
Christian Heimesa342c012008-04-20 21:01:16 +0000760 (such as ``'?'``) to be inserted where there is malformed data. When
761 writing, ``'xmlcharrefreplace'`` (replace with the appropriate XML character
762 reference) or ``'backslashreplace'`` (replace with backslashed escape
763 sequences) can be used. Any other error handling name that has been
764 registered with :func:`codecs.register_error` is also valid.
Georg Brandl014197c2008-04-09 18:40:51 +0000765
766 *newline* can be ``None``, ``''``, ``'\n'``, ``'\r'``, or ``'\r\n'``. It
767 controls the handling of line endings. If it is ``None``, universal newlines
768 is enabled. With this enabled, on input, the lines endings ``'\n'``,
769 ``'\r'``, or ``'\r\n'`` are translated to ``'\n'`` before being returned to
770 the caller. Conversely, on output, ``'\n'`` is translated to the system
Mark Dickinson934896d2009-02-21 20:59:32 +0000771 default line separator, :data:`os.linesep`. If *newline* is any other of its
Georg Brandl014197c2008-04-09 18:40:51 +0000772 legal values, that newline becomes the newline when the file is read and it
773 is returned untranslated. On output, ``'\n'`` is converted to the *newline*.
774
775 If *line_buffering* is ``True``, :meth:`flush` is implied when a call to
776 write contains a newline character.
777
Antoine Pitrou664091b2011-07-23 22:00:03 +0200778 If *write_through* is ``True``, calls to :meth:`write` are guaranteed
779 not to be buffered: any data written on the :class:`TextIOWrapper`
780 object is immediately handled to its underlying binary *buffer*.
781
782 .. versionchanged:: 3.3
783 The *write_through* argument has been added.
784
Victor Stinnerf86a5e82012-06-05 13:43:22 +0200785 .. versionchanged:: 3.3
786 The default *encoding* is now ``locale.getpreferredencoding(False)``
787 instead of ``locale.getpreferredencoding()``. Don't change temporary the
788 locale encoding using :func:`locale.setlocale`, use the current locale
789 encoding instead of the user preferred encoding.
790
Benjamin Peterson0926ad12009-06-06 18:02:12 +0000791 :class:`TextIOWrapper` provides one attribute in addition to those of
Georg Brandl014197c2008-04-09 18:40:51 +0000792 :class:`TextIOBase` and its parents:
793
Georg Brandl014197c2008-04-09 18:40:51 +0000794 .. attribute:: line_buffering
795
796 Whether line buffering is enabled.
Georg Brandl48310cd2009-01-03 21:18:54 +0000797
Georg Brandl014197c2008-04-09 18:40:51 +0000798
Georg Brandl3dd33882009-06-01 17:35:27 +0000799.. class:: StringIO(initial_value='', newline=None)
Georg Brandl014197c2008-04-09 18:40:51 +0000800
Antoine Pitroub530e142010-08-30 12:41:00 +0000801 An in-memory stream for text I/O.
Georg Brandl014197c2008-04-09 18:40:51 +0000802
Benjamin Petersonaa1c8d82009-03-09 02:02:23 +0000803 The initial value of the buffer (an empty string by default) can be set by
804 providing *initial_value*. The *newline* argument works like that of
805 :class:`TextIOWrapper`. The default is to do no newline translation.
Georg Brandl014197c2008-04-09 18:40:51 +0000806
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000807 :class:`StringIO` provides this method in addition to those from
Antoine Pitroub530e142010-08-30 12:41:00 +0000808 :class:`TextIOBase` and its parents:
Georg Brandl014197c2008-04-09 18:40:51 +0000809
810 .. method:: getvalue()
811
Georg Brandl2932d932008-05-30 06:27:09 +0000812 Return a ``str`` containing the entire contents of the buffer at any
813 time before the :class:`StringIO` object's :meth:`close` method is
814 called.
Georg Brandl014197c2008-04-09 18:40:51 +0000815
Georg Brandl2932d932008-05-30 06:27:09 +0000816 Example usage::
817
818 import io
819
820 output = io.StringIO()
821 output.write('First line.\n')
822 print('Second line.', file=output)
823
824 # Retrieve file contents -- this will be
825 # 'First line.\nSecond line.\n'
826 contents = output.getvalue()
827
Georg Brandl48310cd2009-01-03 21:18:54 +0000828 # Close object and discard memory buffer --
Georg Brandl2932d932008-05-30 06:27:09 +0000829 # .getvalue() will now raise an exception.
830 output.close()
Georg Brandl014197c2008-04-09 18:40:51 +0000831
Antoine Pitroub530e142010-08-30 12:41:00 +0000832
Georg Brandl014197c2008-04-09 18:40:51 +0000833.. class:: IncrementalNewlineDecoder
834
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000835 A helper codec that decodes newlines for universal newlines mode. It
836 inherits :class:`codecs.IncrementalDecoder`.
Georg Brandl014197c2008-04-09 18:40:51 +0000837
Antoine Pitroubed81c82010-12-03 19:14:17 +0000838
Antoine Pitroubed81c82010-12-03 19:14:17 +0000839Performance
Benjamin Petersonedf51322011-02-24 03:03:46 +0000840-----------
841
842This section discusses the performance of the provided concrete I/O
843implementations.
Antoine Pitroubed81c82010-12-03 19:14:17 +0000844
845Binary I/O
Benjamin Petersonedf51322011-02-24 03:03:46 +0000846^^^^^^^^^^
Antoine Pitroubed81c82010-12-03 19:14:17 +0000847
Benjamin Petersonedf51322011-02-24 03:03:46 +0000848By reading and writing only large chunks of data even when the user asks for a
849single byte, buffered I/O hides any inefficiency in calling and executing the
850operating system's unbuffered I/O routines. The gain depends on the OS and the
851kind of I/O which is performed. For example, on some modern OSes such as Linux,
852unbuffered disk I/O can be as fast as buffered I/O. The bottom line, however,
853is that buffered I/O offers predictable performance regardless of the platform
854and the backing device. Therefore, it is most always preferable to use buffered
855I/O rather than unbuffered I/O for binary datal
Antoine Pitroubed81c82010-12-03 19:14:17 +0000856
857Text I/O
Benjamin Petersonedf51322011-02-24 03:03:46 +0000858^^^^^^^^
Antoine Pitroubed81c82010-12-03 19:14:17 +0000859
860Text I/O over a binary storage (such as a file) is significantly slower than
Benjamin Petersonedf51322011-02-24 03:03:46 +0000861binary I/O over the same storage, because it requires conversions between
862unicode and binary data using a character codec. This can become noticeable
863handling huge amounts of text data like large log files. Also,
864:meth:`TextIOWrapper.tell` and :meth:`TextIOWrapper.seek` are both quite slow
865due to the reconstruction algorithm used.
Antoine Pitroubed81c82010-12-03 19:14:17 +0000866
867:class:`StringIO`, however, is a native in-memory unicode container and will
868exhibit similar speed to :class:`BytesIO`.
869
870Multi-threading
871^^^^^^^^^^^^^^^
872
Benjamin Petersonedf51322011-02-24 03:03:46 +0000873:class:`FileIO` objects are thread-safe to the extent that the operating system
874calls (such as ``read(2)`` under Unix) they wrap are thread-safe too.
Antoine Pitroubed81c82010-12-03 19:14:17 +0000875
876Binary buffered objects (instances of :class:`BufferedReader`,
877:class:`BufferedWriter`, :class:`BufferedRandom` and :class:`BufferedRWPair`)
878protect their internal structures using a lock; it is therefore safe to call
879them from multiple threads at once.
880
881:class:`TextIOWrapper` objects are not thread-safe.
882
883Reentrancy
884^^^^^^^^^^
885
886Binary buffered objects (instances of :class:`BufferedReader`,
887:class:`BufferedWriter`, :class:`BufferedRandom` and :class:`BufferedRWPair`)
888are not reentrant. While reentrant calls will not happen in normal situations,
Benjamin Petersonedf51322011-02-24 03:03:46 +0000889they can arise from doing I/O in a :mod:`signal` handler. If a thread tries to
890renter a buffered object which it is already accessing, a :exc:`RuntimeError` is
891raised. Note this doesn't prohibit a different thread from entering the
892buffered object.
Antoine Pitroubed81c82010-12-03 19:14:17 +0000893
Benjamin Petersonedf51322011-02-24 03:03:46 +0000894The above implicitly extends to text files, since the :func:`open()` function
895will wrap a buffered object inside a :class:`TextIOWrapper`. This includes
896standard streams and therefore affects the built-in function :func:`print()` as
897well.
Antoine Pitroubed81c82010-12-03 19:14:17 +0000898