blob: 4d564bb3f9011d3cc95f0ca642bfd8c92252d9c4 [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
Georg Brandl014197c2008-04-09 18:40:51 +0000294 .. method:: seekable()
295
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000296 Return ``True`` if the stream supports random access. If ``False``,
Antoine Pitroua787b652011-10-12 19:02:52 +0200297 :meth:`seek`, :meth:`tell` and :meth:`truncate` will raise :exc:`OSError`.
Georg Brandl014197c2008-04-09 18:40:51 +0000298
299 .. method:: tell()
300
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000301 Return the current stream position.
Georg Brandl014197c2008-04-09 18:40:51 +0000302
Georg Brandl3dd33882009-06-01 17:35:27 +0000303 .. method:: truncate(size=None)
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000304
Antoine Pitrou2016dc92010-05-29 12:08:25 +0000305 Resize the stream to the given *size* in bytes (or the current position
306 if *size* is not specified). The current stream position isn't changed.
307 This resizing can extend or reduce the current file size. In case of
308 extension, the contents of the new file area depend on the platform
309 (on most systems, additional bytes are zero-filled, on Windows they're
310 undetermined). The new file size is returned.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000311
Georg Brandl014197c2008-04-09 18:40:51 +0000312 .. method:: writable()
313
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000314 Return ``True`` if the stream supports writing. If ``False``,
Antoine Pitroua787b652011-10-12 19:02:52 +0200315 :meth:`write` and :meth:`truncate` will raise :exc:`OSError`.
Georg Brandl014197c2008-04-09 18:40:51 +0000316
317 .. method:: writelines(lines)
318
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000319 Write a list of lines to the stream. Line separators are not added, so it
320 is usual for each of the lines provided to have a line separator at the
321 end.
Georg Brandl014197c2008-04-09 18:40:51 +0000322
323
324.. class:: RawIOBase
325
326 Base class for raw binary I/O. It inherits :class:`IOBase`. There is no
327 public constructor.
328
Antoine Pitrou497a7672009-09-17 17:18:01 +0000329 Raw binary I/O typically provides low-level access to an underlying OS
330 device or API, and does not try to encapsulate it in high-level primitives
331 (this is left to Buffered I/O and Text I/O, described later in this page).
332
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000333 In addition to the attributes and methods from :class:`IOBase`,
334 RawIOBase provides the following methods:
Georg Brandl014197c2008-04-09 18:40:51 +0000335
Georg Brandl3dd33882009-06-01 17:35:27 +0000336 .. method:: read(n=-1)
Georg Brandl014197c2008-04-09 18:40:51 +0000337
Antoine Pitrou78ddbe62009-10-01 16:24:45 +0000338 Read up to *n* bytes from the object and return them. As a convenience,
339 if *n* is unspecified or -1, :meth:`readall` is called. Otherwise,
340 only one system call is ever made. Fewer than *n* bytes may be
341 returned if the operating system call returns fewer than *n* bytes.
342
343 If 0 bytes are returned, and *n* was not 0, this indicates end of file.
344 If the object is in non-blocking mode and no bytes are available,
345 ``None`` is returned.
Georg Brandl014197c2008-04-09 18:40:51 +0000346
Benjamin Petersonb47aace2008-04-09 21:38:38 +0000347 .. method:: readall()
Georg Brandl014197c2008-04-09 18:40:51 +0000348
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000349 Read and return all the bytes from the stream until EOF, using multiple
350 calls to the stream if necessary.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000351
352 .. method:: readinto(b)
353
Daniel Stutzbachd01df462010-11-30 17:49:53 +0000354 Read up to len(b) bytes into bytearray *b* and return the number
355 of bytes read. If the object is in non-blocking mode and no
356 bytes are available, ``None`` is returned.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000357
358 .. method:: write(b)
359
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000360 Write the given bytes or bytearray object, *b*, to the underlying raw
Antoine Pitrou497a7672009-09-17 17:18:01 +0000361 stream and return the number of bytes written. This can be less than
362 ``len(b)``, depending on specifics of the underlying raw stream, and
363 especially if it is in non-blocking mode. ``None`` is returned if the
364 raw stream is set not to block and no single byte could be readily
365 written to it.
Georg Brandl014197c2008-04-09 18:40:51 +0000366
367
Georg Brandl014197c2008-04-09 18:40:51 +0000368.. class:: BufferedIOBase
369
Antoine Pitrou497a7672009-09-17 17:18:01 +0000370 Base class for binary streams that support some kind of buffering.
371 It inherits :class:`IOBase`. There is no public constructor.
Georg Brandl014197c2008-04-09 18:40:51 +0000372
Antoine Pitrou497a7672009-09-17 17:18:01 +0000373 The main difference with :class:`RawIOBase` is that methods :meth:`read`,
374 :meth:`readinto` and :meth:`write` will try (respectively) to read as much
375 input as requested or to consume all given output, at the expense of
376 making perhaps more than one system call.
377
378 In addition, those methods can raise :exc:`BlockingIOError` if the
379 underlying raw stream is in non-blocking mode and cannot take or give
380 enough data; unlike their :class:`RawIOBase` counterparts, they will
381 never return ``None``.
382
383 Besides, the :meth:`read` method does not have a default
Georg Brandl014197c2008-04-09 18:40:51 +0000384 implementation that defers to :meth:`readinto`.
385
Antoine Pitrou497a7672009-09-17 17:18:01 +0000386 A typical :class:`BufferedIOBase` implementation should not inherit from a
387 :class:`RawIOBase` implementation, but wrap one, like
388 :class:`BufferedWriter` and :class:`BufferedReader` do.
Georg Brandl014197c2008-04-09 18:40:51 +0000389
Senthil Kumarana6bac952011-07-04 11:28:30 -0700390 :class:`BufferedIOBase` provides or overrides these methods and attribute in
391 addition to those from :class:`IOBase`:
Georg Brandl014197c2008-04-09 18:40:51 +0000392
Benjamin Petersonc609b6b2009-06-28 17:32:20 +0000393 .. attribute:: raw
394
395 The underlying raw stream (a :class:`RawIOBase` instance) that
396 :class:`BufferedIOBase` deals with. This is not part of the
397 :class:`BufferedIOBase` API and may not exist on some implementations.
398
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000399 .. method:: detach()
400
401 Separate the underlying raw stream from the buffer and return it.
402
403 After the raw stream has been detached, the buffer is in an unusable
404 state.
405
406 Some buffers, like :class:`BytesIO`, do not have the concept of a single
407 raw stream to return from this method. They raise
408 :exc:`UnsupportedOperation`.
409
Benjamin Petersonedc36472009-05-01 20:48:14 +0000410 .. versionadded:: 3.1
411
Georg Brandl3dd33882009-06-01 17:35:27 +0000412 .. method:: read(n=-1)
Georg Brandl014197c2008-04-09 18:40:51 +0000413
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000414 Read and return up to *n* bytes. If the argument is omitted, ``None``, or
Georg Brandl014197c2008-04-09 18:40:51 +0000415 negative, data is read and returned until EOF is reached. An empty bytes
416 object is returned if the stream is already at EOF.
417
418 If the argument is positive, and the underlying raw stream is not
419 interactive, multiple raw reads may be issued to satisfy the byte count
420 (unless EOF is reached first). But for interactive raw streams, at most
421 one raw read will be issued, and a short result does not imply that EOF is
422 imminent.
423
Antoine Pitrou497a7672009-09-17 17:18:01 +0000424 A :exc:`BlockingIOError` is raised if the underlying raw stream is in
425 non blocking-mode, and has no data available at the moment.
Georg Brandl014197c2008-04-09 18:40:51 +0000426
Georg Brandl3dd33882009-06-01 17:35:27 +0000427 .. method:: read1(n=-1)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000428
429 Read and return up to *n* bytes, with at most one call to the underlying
Antoine Pitrou497a7672009-09-17 17:18:01 +0000430 raw stream's :meth:`~RawIOBase.read` method. This can be useful if you
431 are implementing your own buffering on top of a :class:`BufferedIOBase`
432 object.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000433
Georg Brandl014197c2008-04-09 18:40:51 +0000434 .. method:: readinto(b)
435
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000436 Read up to len(b) bytes into bytearray *b* and return the number of bytes
Georg Brandl014197c2008-04-09 18:40:51 +0000437 read.
438
439 Like :meth:`read`, multiple reads may be issued to the underlying raw
Antoine Pitrou497a7672009-09-17 17:18:01 +0000440 stream, unless the latter is 'interactive'.
Georg Brandl014197c2008-04-09 18:40:51 +0000441
Antoine Pitrou497a7672009-09-17 17:18:01 +0000442 A :exc:`BlockingIOError` is raised if the underlying raw stream is in
443 non blocking-mode, and has no data available at the moment.
Georg Brandl014197c2008-04-09 18:40:51 +0000444
Georg Brandl014197c2008-04-09 18:40:51 +0000445 .. method:: write(b)
446
Antoine Pitrou497a7672009-09-17 17:18:01 +0000447 Write the given bytes or bytearray object, *b* and return the number
448 of bytes written (never less than ``len(b)``, since if the write fails
Antoine Pitroua787b652011-10-12 19:02:52 +0200449 an :exc:`OSError` will be raised). Depending on the actual
Antoine Pitrou497a7672009-09-17 17:18:01 +0000450 implementation, these bytes may be readily written to the underlying
451 stream, or held in a buffer for performance and latency reasons.
Georg Brandl014197c2008-04-09 18:40:51 +0000452
Antoine Pitrou497a7672009-09-17 17:18:01 +0000453 When in non-blocking mode, a :exc:`BlockingIOError` is raised if the
454 data needed to be written to the raw stream but it couldn't accept
455 all the data without blocking.
Georg Brandl014197c2008-04-09 18:40:51 +0000456
457
Benjamin Petersonaa069002009-01-23 03:26:36 +0000458Raw File I/O
Antoine Pitroub530e142010-08-30 12:41:00 +0000459^^^^^^^^^^^^
Benjamin Petersonaa069002009-01-23 03:26:36 +0000460
Ross Lagerwall59142db2011-10-31 20:34:46 +0200461.. class:: FileIO(name, mode='r', closefd=True, opener=None)
Benjamin Petersonaa069002009-01-23 03:26:36 +0000462
Antoine Pitrou497a7672009-09-17 17:18:01 +0000463 :class:`FileIO` represents an OS-level file containing bytes data.
464 It implements the :class:`RawIOBase` interface (and therefore the
465 :class:`IOBase` interface, too).
466
467 The *name* can be one of two things:
468
469 * a character string or bytes object representing the path to the file
470 which will be opened;
471 * an integer representing the number of an existing OS-level file descriptor
472 to which the resulting :class:`FileIO` object will give access.
Benjamin Petersonaa069002009-01-23 03:26:36 +0000473
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100474 The *mode* can be ``'r'``, ``'w'``, ``'x'`` or ``'a'`` for reading
Charles-François Natalid612de12012-01-14 11:51:00 +0100475 (default), writing, exclusive creation or appending. The file will be
476 created if it doesn't exist when opened for writing or appending; it will be
477 truncated when opened for writing. :exc:`FileExistsError` will be raised if
478 it already exists when opened for creating. Opening a file for creating
479 implies writing, so this mode behaves in a similar way to ``'w'``. Add a
480 ``'+'`` to the mode to allow simultaneous reading and writing.
Benjamin Petersonaa069002009-01-23 03:26:36 +0000481
Antoine Pitrou497a7672009-09-17 17:18:01 +0000482 The :meth:`read` (when called with a positive argument), :meth:`readinto`
483 and :meth:`write` methods on this class will only make one system call.
484
Ross Lagerwall59142db2011-10-31 20:34:46 +0200485 A custom opener can be used by passing a callable as *opener*. The underlying
486 file descriptor for the file object is then obtained by calling *opener* with
487 (*name*, *flags*). *opener* must return an open file descriptor (passing
488 :mod:`os.open` as *opener* results in functionality similar to passing
489 ``None``).
490
491 .. versionchanged:: 3.3
492 The *opener* parameter was added.
Charles-François Natalidc3044c2012-01-09 22:40:02 +0100493 The ``'x'`` mode was added.
Ross Lagerwall59142db2011-10-31 20:34:46 +0200494
Benjamin Petersonaa069002009-01-23 03:26:36 +0000495 In addition to the attributes and methods from :class:`IOBase` and
496 :class:`RawIOBase`, :class:`FileIO` provides the following data
497 attributes and methods:
498
499 .. attribute:: mode
500
501 The mode as given in the constructor.
502
503 .. attribute:: name
504
505 The file name. This is the file descriptor of the file when no name is
506 given in the constructor.
507
Benjamin Petersonaa069002009-01-23 03:26:36 +0000508
509Buffered Streams
Antoine Pitroub530e142010-08-30 12:41:00 +0000510^^^^^^^^^^^^^^^^
Benjamin Petersonaa069002009-01-23 03:26:36 +0000511
Antoine Pitroubed81c82010-12-03 19:14:17 +0000512Buffered I/O streams provide a higher-level interface to an I/O device
513than raw I/O does.
Antoine Pitrou497a7672009-09-17 17:18:01 +0000514
Georg Brandl014197c2008-04-09 18:40:51 +0000515.. class:: BytesIO([initial_bytes])
516
517 A stream implementation using an in-memory bytes buffer. It inherits
518 :class:`BufferedIOBase`.
519
Antoine Pitroub530e142010-08-30 12:41:00 +0000520 The argument *initial_bytes* contains optional initial :class:`bytes` data.
Georg Brandl014197c2008-04-09 18:40:51 +0000521
522 :class:`BytesIO` provides or overrides these methods in addition to those
523 from :class:`BufferedIOBase` and :class:`IOBase`:
524
Antoine Pitrou972ee132010-09-06 18:48:21 +0000525 .. method:: getbuffer()
526
527 Return a readable and writable view over the contents of the buffer
528 without copying them. Also, mutating the view will transparently
529 update the contents of the buffer::
530
531 >>> b = io.BytesIO(b"abcdef")
532 >>> view = b.getbuffer()
533 >>> view[2:4] = b"56"
534 >>> b.getvalue()
535 b'ab56ef'
536
537 .. note::
538 As long as the view exists, the :class:`BytesIO` object cannot be
539 resized.
540
541 .. versionadded:: 3.2
542
Georg Brandl014197c2008-04-09 18:40:51 +0000543 .. method:: getvalue()
544
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000545 Return ``bytes`` containing the entire contents of the buffer.
Georg Brandl014197c2008-04-09 18:40:51 +0000546
547 .. method:: read1()
548
Benjamin Peterson9efcc4b2008-04-14 21:30:21 +0000549 In :class:`BytesIO`, this is the same as :meth:`read`.
Georg Brandl014197c2008-04-09 18:40:51 +0000550
Georg Brandl014197c2008-04-09 18:40:51 +0000551
Georg Brandl3dd33882009-06-01 17:35:27 +0000552.. class:: BufferedReader(raw, buffer_size=DEFAULT_BUFFER_SIZE)
Georg Brandl014197c2008-04-09 18:40:51 +0000553
Antoine Pitrou497a7672009-09-17 17:18:01 +0000554 A buffer providing higher-level access to a readable, sequential
555 :class:`RawIOBase` object. It inherits :class:`BufferedIOBase`.
556 When reading data from this object, a larger amount of data may be
557 requested from the underlying raw stream, and kept in an internal buffer.
558 The buffered data can then be returned directly on subsequent reads.
Georg Brandl014197c2008-04-09 18:40:51 +0000559
560 The constructor creates a :class:`BufferedReader` for the given readable
561 *raw* stream and *buffer_size*. If *buffer_size* is omitted,
562 :data:`DEFAULT_BUFFER_SIZE` is used.
563
564 :class:`BufferedReader` provides or overrides these methods in addition to
565 those from :class:`BufferedIOBase` and :class:`IOBase`:
566
567 .. method:: peek([n])
568
Benjamin Petersonc43a26d2009-06-16 23:09:24 +0000569 Return bytes from the stream without advancing the position. At most one
Benjamin Peterson2a8b54d2009-06-14 14:37:23 +0000570 single read on the raw stream is done to satisfy the call. The number of
571 bytes returned may be less or more than requested.
Georg Brandl014197c2008-04-09 18:40:51 +0000572
573 .. method:: read([n])
574
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000575 Read and return *n* bytes, or if *n* is not given or negative, until EOF
Georg Brandl014197c2008-04-09 18:40:51 +0000576 or if the read call would block in non-blocking mode.
577
578 .. method:: read1(n)
579
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000580 Read and return up to *n* bytes with only one call on the raw stream. If
Georg Brandl014197c2008-04-09 18:40:51 +0000581 at least one byte is buffered, only buffered bytes are returned.
582 Otherwise, one raw stream read call is made.
583
584
Georg Brandl3dd33882009-06-01 17:35:27 +0000585.. class:: BufferedWriter(raw, buffer_size=DEFAULT_BUFFER_SIZE)
Georg Brandl014197c2008-04-09 18:40:51 +0000586
Antoine Pitrou497a7672009-09-17 17:18:01 +0000587 A buffer providing higher-level access to a writeable, sequential
588 :class:`RawIOBase` object. It inherits :class:`BufferedIOBase`.
589 When writing to this object, data is normally held into an internal
590 buffer. The buffer will be written out to the underlying :class:`RawIOBase`
591 object under various conditions, including:
592
593 * when the buffer gets too small for all pending data;
594 * when :meth:`flush()` is called;
595 * when a :meth:`seek()` is requested (for :class:`BufferedRandom` objects);
596 * when the :class:`BufferedWriter` object is closed or destroyed.
Georg Brandl014197c2008-04-09 18:40:51 +0000597
598 The constructor creates a :class:`BufferedWriter` for the given writeable
599 *raw* stream. If the *buffer_size* is not given, it defaults to
Benjamin Peterson394ee002009-03-05 22:33:59 +0000600 :data:`DEFAULT_BUFFER_SIZE`.
601
Georg Brandl3dd33882009-06-01 17:35:27 +0000602 A third argument, *max_buffer_size*, is supported, but unused and deprecated.
Georg Brandl014197c2008-04-09 18:40:51 +0000603
604 :class:`BufferedWriter` provides or overrides these methods in addition to
605 those from :class:`BufferedIOBase` and :class:`IOBase`:
606
607 .. method:: flush()
608
609 Force bytes held in the buffer into the raw stream. A
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000610 :exc:`BlockingIOError` should be raised if the raw stream blocks.
Georg Brandl014197c2008-04-09 18:40:51 +0000611
612 .. method:: write(b)
613
Antoine Pitrou497a7672009-09-17 17:18:01 +0000614 Write the bytes or bytearray object, *b* and return the number of bytes
615 written. When in non-blocking mode, a :exc:`BlockingIOError` is raised
616 if the buffer needs to be written out but the raw stream blocks.
Georg Brandl014197c2008-04-09 18:40:51 +0000617
618
Georg Brandl3dd33882009-06-01 17:35:27 +0000619.. class:: BufferedRandom(raw, buffer_size=DEFAULT_BUFFER_SIZE)
Georg Brandl014197c2008-04-09 18:40:51 +0000620
621 A buffered interface to random access streams. It inherits
Antoine Pitrou497a7672009-09-17 17:18:01 +0000622 :class:`BufferedReader` and :class:`BufferedWriter`, and further supports
623 :meth:`seek` and :meth:`tell` functionality.
Georg Brandl014197c2008-04-09 18:40:51 +0000624
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000625 The constructor creates a reader and writer for a seekable raw stream, given
Georg Brandl014197c2008-04-09 18:40:51 +0000626 in the first argument. If the *buffer_size* is omitted it defaults to
Benjamin Peterson394ee002009-03-05 22:33:59 +0000627 :data:`DEFAULT_BUFFER_SIZE`.
628
Georg Brandl3dd33882009-06-01 17:35:27 +0000629 A third argument, *max_buffer_size*, is supported, but unused and deprecated.
Georg Brandl014197c2008-04-09 18:40:51 +0000630
631 :class:`BufferedRandom` is capable of anything :class:`BufferedReader` or
632 :class:`BufferedWriter` can do.
633
634
Antoine Pitrou13d28952011-08-20 19:48:43 +0200635.. class:: BufferedRWPair(reader, writer, buffer_size=DEFAULT_BUFFER_SIZE)
636
637 A buffered I/O object combining two unidirectional :class:`RawIOBase`
638 objects -- one readable, the other writeable -- into a single bidirectional
639 endpoint. It inherits :class:`BufferedIOBase`.
640
641 *reader* and *writer* are :class:`RawIOBase` objects that are readable and
642 writeable respectively. If the *buffer_size* is omitted it defaults to
643 :data:`DEFAULT_BUFFER_SIZE`.
644
645 A fourth argument, *max_buffer_size*, is supported, but unused and
646 deprecated.
647
648 :class:`BufferedRWPair` implements all of :class:`BufferedIOBase`\'s methods
649 except for :meth:`~BufferedIOBase.detach`, which raises
650 :exc:`UnsupportedOperation`.
651
652 .. warning::
653 :class:`BufferedRWPair` does not attempt to synchronize accesses to
654 its underlying raw streams. You should not pass it the same object
655 as reader and writer; use :class:`BufferedRandom` instead.
656
657
Georg Brandl014197c2008-04-09 18:40:51 +0000658Text I/O
Antoine Pitroub530e142010-08-30 12:41:00 +0000659^^^^^^^^
Georg Brandl014197c2008-04-09 18:40:51 +0000660
661.. class:: TextIOBase
662
663 Base class for text streams. This class provides a character and line based
664 interface to stream I/O. There is no :meth:`readinto` method because
665 Python's character strings are immutable. It inherits :class:`IOBase`.
666 There is no public constructor.
667
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000668 :class:`TextIOBase` provides or overrides these data attributes and
669 methods in addition to those from :class:`IOBase`:
Georg Brandl014197c2008-04-09 18:40:51 +0000670
671 .. attribute:: encoding
672
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000673 The name of the encoding used to decode the stream's bytes into
Georg Brandl014197c2008-04-09 18:40:51 +0000674 strings, and to encode strings into bytes.
675
Benjamin Peterson0926ad12009-06-06 18:02:12 +0000676 .. attribute:: errors
677
678 The error setting of the decoder or encoder.
679
Georg Brandl014197c2008-04-09 18:40:51 +0000680 .. attribute:: newlines
681
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000682 A string, a tuple of strings, or ``None``, indicating the newlines
Antoine Pitrou497a7672009-09-17 17:18:01 +0000683 translated so far. Depending on the implementation and the initial
684 constructor flags, this may not be available.
Georg Brandl014197c2008-04-09 18:40:51 +0000685
Benjamin Petersonc609b6b2009-06-28 17:32:20 +0000686 .. attribute:: buffer
687
688 The underlying binary buffer (a :class:`BufferedIOBase` instance) that
689 :class:`TextIOBase` deals with. This is not part of the
690 :class:`TextIOBase` API and may not exist on some implementations.
691
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000692 .. method:: detach()
693
Antoine Pitrou497a7672009-09-17 17:18:01 +0000694 Separate the underlying binary buffer from the :class:`TextIOBase` and
695 return it.
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000696
697 After the underlying buffer has been detached, the :class:`TextIOBase` is
698 in an unusable state.
699
700 Some :class:`TextIOBase` implementations, like :class:`StringIO`, may not
701 have the concept of an underlying buffer and calling this method will
702 raise :exc:`UnsupportedOperation`.
703
Benjamin Petersonedc36472009-05-01 20:48:14 +0000704 .. versionadded:: 3.1
705
Georg Brandl014197c2008-04-09 18:40:51 +0000706 .. method:: read(n)
707
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000708 Read and return at most *n* characters from the stream as a single
Antoine Pitrou497a7672009-09-17 17:18:01 +0000709 :class:`str`. If *n* is negative or ``None``, reads until EOF.
Georg Brandl014197c2008-04-09 18:40:51 +0000710
711 .. method:: readline()
712
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000713 Read until newline or EOF and return a single ``str``. If the stream is
714 already at EOF, an empty string is returned.
Georg Brandl014197c2008-04-09 18:40:51 +0000715
Antoine Pitrouf49d1522012-01-21 20:20:49 +0100716 .. method:: seek(offset, whence=SEEK_SET)
717
718 Change the stream position to the given *offset*. Behaviour depends
719 on the *whence* parameter:
720
721 * :data:`SEEK_SET` or ``0``: seek from the start of the stream
722 (the default); *offset* must either be a number returned by
723 :meth:`TextIOBase.tell`, or zero. Any other *offset* value
724 produces undefined behaviour.
725 * :data:`SEEK_CUR` or ``1``: "seek" to the current position;
726 *offset* must be zero, which is a no-operation (all other values
727 are unsupported).
728 * :data:`SEEK_END` or ``2``: seek to the end of the stream;
729 *offset* must be zero (all other values are unsupported).
730
731 Return the new absolute position as an opaque number.
732
733 .. versionadded:: 3.1
734 The ``SEEK_*`` constants.
735
736 .. method:: tell()
737
738 Return the current stream position as an opaque number. The number
739 does not usually represent a number of bytes in the underlying
740 binary storage.
741
Georg Brandl014197c2008-04-09 18:40:51 +0000742 .. method:: write(s)
743
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000744 Write the string *s* to the stream and return the number of characters
745 written.
Georg Brandl014197c2008-04-09 18:40:51 +0000746
747
Antoine Pitrou664091b2011-07-23 22:00:03 +0200748.. class:: TextIOWrapper(buffer, encoding=None, errors=None, newline=None, \
749 line_buffering=False, write_through=False)
Georg Brandl014197c2008-04-09 18:40:51 +0000750
Antoine Pitrou497a7672009-09-17 17:18:01 +0000751 A buffered text stream over a :class:`BufferedIOBase` binary stream.
Georg Brandl014197c2008-04-09 18:40:51 +0000752 It inherits :class:`TextIOBase`.
753
754 *encoding* gives the name of the encoding that the stream will be decoded or
755 encoded with. It defaults to :func:`locale.getpreferredencoding`.
756
Benjamin Petersonb85a5842008-04-13 21:39:58 +0000757 *errors* is an optional string that specifies how encoding and decoding
758 errors are to be handled. Pass ``'strict'`` to raise a :exc:`ValueError`
759 exception if there is an encoding error (the default of ``None`` has the same
760 effect), or pass ``'ignore'`` to ignore errors. (Note that ignoring encoding
761 errors can lead to data loss.) ``'replace'`` causes a replacement marker
Christian Heimesa342c012008-04-20 21:01:16 +0000762 (such as ``'?'``) to be inserted where there is malformed data. When
763 writing, ``'xmlcharrefreplace'`` (replace with the appropriate XML character
764 reference) or ``'backslashreplace'`` (replace with backslashed escape
765 sequences) can be used. Any other error handling name that has been
766 registered with :func:`codecs.register_error` is also valid.
Georg Brandl014197c2008-04-09 18:40:51 +0000767
768 *newline* can be ``None``, ``''``, ``'\n'``, ``'\r'``, or ``'\r\n'``. It
769 controls the handling of line endings. If it is ``None``, universal newlines
770 is enabled. With this enabled, on input, the lines endings ``'\n'``,
771 ``'\r'``, or ``'\r\n'`` are translated to ``'\n'`` before being returned to
772 the caller. Conversely, on output, ``'\n'`` is translated to the system
Mark Dickinson934896d2009-02-21 20:59:32 +0000773 default line separator, :data:`os.linesep`. If *newline* is any other of its
Georg Brandl014197c2008-04-09 18:40:51 +0000774 legal values, that newline becomes the newline when the file is read and it
775 is returned untranslated. On output, ``'\n'`` is converted to the *newline*.
776
777 If *line_buffering* is ``True``, :meth:`flush` is implied when a call to
778 write contains a newline character.
779
Antoine Pitrou664091b2011-07-23 22:00:03 +0200780 If *write_through* is ``True``, calls to :meth:`write` are guaranteed
781 not to be buffered: any data written on the :class:`TextIOWrapper`
782 object is immediately handled to its underlying binary *buffer*.
783
784 .. versionchanged:: 3.3
785 The *write_through* argument has been added.
786
Benjamin Peterson0926ad12009-06-06 18:02:12 +0000787 :class:`TextIOWrapper` provides one attribute in addition to those of
Georg Brandl014197c2008-04-09 18:40:51 +0000788 :class:`TextIOBase` and its parents:
789
Georg Brandl014197c2008-04-09 18:40:51 +0000790 .. attribute:: line_buffering
791
792 Whether line buffering is enabled.
Georg Brandl48310cd2009-01-03 21:18:54 +0000793
Georg Brandl014197c2008-04-09 18:40:51 +0000794
Georg Brandl3dd33882009-06-01 17:35:27 +0000795.. class:: StringIO(initial_value='', newline=None)
Georg Brandl014197c2008-04-09 18:40:51 +0000796
Antoine Pitroub530e142010-08-30 12:41:00 +0000797 An in-memory stream for text I/O.
Georg Brandl014197c2008-04-09 18:40:51 +0000798
Benjamin Petersonaa1c8d82009-03-09 02:02:23 +0000799 The initial value of the buffer (an empty string by default) can be set by
800 providing *initial_value*. The *newline* argument works like that of
801 :class:`TextIOWrapper`. The default is to do no newline translation.
Georg Brandl014197c2008-04-09 18:40:51 +0000802
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000803 :class:`StringIO` provides this method in addition to those from
Antoine Pitroub530e142010-08-30 12:41:00 +0000804 :class:`TextIOBase` and its parents:
Georg Brandl014197c2008-04-09 18:40:51 +0000805
806 .. method:: getvalue()
807
Georg Brandl2932d932008-05-30 06:27:09 +0000808 Return a ``str`` containing the entire contents of the buffer at any
809 time before the :class:`StringIO` object's :meth:`close` method is
810 called.
Georg Brandl014197c2008-04-09 18:40:51 +0000811
Georg Brandl2932d932008-05-30 06:27:09 +0000812 Example usage::
813
814 import io
815
816 output = io.StringIO()
817 output.write('First line.\n')
818 print('Second line.', file=output)
819
820 # Retrieve file contents -- this will be
821 # 'First line.\nSecond line.\n'
822 contents = output.getvalue()
823
Georg Brandl48310cd2009-01-03 21:18:54 +0000824 # Close object and discard memory buffer --
Georg Brandl2932d932008-05-30 06:27:09 +0000825 # .getvalue() will now raise an exception.
826 output.close()
Georg Brandl014197c2008-04-09 18:40:51 +0000827
Antoine Pitroub530e142010-08-30 12:41:00 +0000828
Georg Brandl014197c2008-04-09 18:40:51 +0000829.. class:: IncrementalNewlineDecoder
830
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000831 A helper codec that decodes newlines for universal newlines mode. It
832 inherits :class:`codecs.IncrementalDecoder`.
Georg Brandl014197c2008-04-09 18:40:51 +0000833
Antoine Pitroubed81c82010-12-03 19:14:17 +0000834
Antoine Pitroubed81c82010-12-03 19:14:17 +0000835Performance
Benjamin Petersonedf51322011-02-24 03:03:46 +0000836-----------
837
838This section discusses the performance of the provided concrete I/O
839implementations.
Antoine Pitroubed81c82010-12-03 19:14:17 +0000840
841Binary I/O
Benjamin Petersonedf51322011-02-24 03:03:46 +0000842^^^^^^^^^^
Antoine Pitroubed81c82010-12-03 19:14:17 +0000843
Benjamin Petersonedf51322011-02-24 03:03:46 +0000844By reading and writing only large chunks of data even when the user asks for a
845single byte, buffered I/O hides any inefficiency in calling and executing the
846operating system's unbuffered I/O routines. The gain depends on the OS and the
847kind of I/O which is performed. For example, on some modern OSes such as Linux,
848unbuffered disk I/O can be as fast as buffered I/O. The bottom line, however,
849is that buffered I/O offers predictable performance regardless of the platform
850and the backing device. Therefore, it is most always preferable to use buffered
851I/O rather than unbuffered I/O for binary datal
Antoine Pitroubed81c82010-12-03 19:14:17 +0000852
853Text I/O
Benjamin Petersonedf51322011-02-24 03:03:46 +0000854^^^^^^^^
Antoine Pitroubed81c82010-12-03 19:14:17 +0000855
856Text I/O over a binary storage (such as a file) is significantly slower than
Benjamin Petersonedf51322011-02-24 03:03:46 +0000857binary I/O over the same storage, because it requires conversions between
858unicode and binary data using a character codec. This can become noticeable
859handling huge amounts of text data like large log files. Also,
860:meth:`TextIOWrapper.tell` and :meth:`TextIOWrapper.seek` are both quite slow
861due to the reconstruction algorithm used.
Antoine Pitroubed81c82010-12-03 19:14:17 +0000862
863:class:`StringIO`, however, is a native in-memory unicode container and will
864exhibit similar speed to :class:`BytesIO`.
865
866Multi-threading
867^^^^^^^^^^^^^^^
868
Benjamin Petersonedf51322011-02-24 03:03:46 +0000869:class:`FileIO` objects are thread-safe to the extent that the operating system
870calls (such as ``read(2)`` under Unix) they wrap are thread-safe too.
Antoine Pitroubed81c82010-12-03 19:14:17 +0000871
872Binary buffered objects (instances of :class:`BufferedReader`,
873:class:`BufferedWriter`, :class:`BufferedRandom` and :class:`BufferedRWPair`)
874protect their internal structures using a lock; it is therefore safe to call
875them from multiple threads at once.
876
877:class:`TextIOWrapper` objects are not thread-safe.
878
879Reentrancy
880^^^^^^^^^^
881
882Binary buffered objects (instances of :class:`BufferedReader`,
883:class:`BufferedWriter`, :class:`BufferedRandom` and :class:`BufferedRWPair`)
884are not reentrant. While reentrant calls will not happen in normal situations,
Benjamin Petersonedf51322011-02-24 03:03:46 +0000885they can arise from doing I/O in a :mod:`signal` handler. If a thread tries to
886renter a buffered object which it is already accessing, a :exc:`RuntimeError` is
887raised. Note this doesn't prohibit a different thread from entering the
888buffered object.
Antoine Pitroubed81c82010-12-03 19:14:17 +0000889
Benjamin Petersonedf51322011-02-24 03:03:46 +0000890The above implicitly extends to text files, since the :func:`open()` function
891will wrap a buffered object inside a :class:`TextIOWrapper`. This includes
892standard streams and therefore affects the built-in function :func:`print()` as
893well.
Antoine Pitroubed81c82010-12-03 19:14:17 +0000894