blob: 0bcf687ac9d35d1b82268309dd696bf0dff5c480 [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
216 strings). See :meth:`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
Georg Brandl3dd33882009-06-01 17:35:27 +0000461.. class:: FileIO(name, mode='r', closefd=True)
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
474 The *mode* can be ``'r'``, ``'w'`` or ``'a'`` for reading (default), writing,
475 or appending. The file will be created if it doesn't exist when opened for
476 writing or appending; it will be truncated when opened for writing. Add a
477 ``'+'`` to the mode to allow simultaneous reading and writing.
478
Antoine Pitrou497a7672009-09-17 17:18:01 +0000479 The :meth:`read` (when called with a positive argument), :meth:`readinto`
480 and :meth:`write` methods on this class will only make one system call.
481
Benjamin Petersonaa069002009-01-23 03:26:36 +0000482 In addition to the attributes and methods from :class:`IOBase` and
483 :class:`RawIOBase`, :class:`FileIO` provides the following data
484 attributes and methods:
485
486 .. attribute:: mode
487
488 The mode as given in the constructor.
489
490 .. attribute:: name
491
492 The file name. This is the file descriptor of the file when no name is
493 given in the constructor.
494
Benjamin Petersonaa069002009-01-23 03:26:36 +0000495
496Buffered Streams
Antoine Pitroub530e142010-08-30 12:41:00 +0000497^^^^^^^^^^^^^^^^
Benjamin Petersonaa069002009-01-23 03:26:36 +0000498
Antoine Pitroubed81c82010-12-03 19:14:17 +0000499Buffered I/O streams provide a higher-level interface to an I/O device
500than raw I/O does.
Antoine Pitrou497a7672009-09-17 17:18:01 +0000501
Georg Brandl014197c2008-04-09 18:40:51 +0000502.. class:: BytesIO([initial_bytes])
503
504 A stream implementation using an in-memory bytes buffer. It inherits
505 :class:`BufferedIOBase`.
506
Antoine Pitroub530e142010-08-30 12:41:00 +0000507 The argument *initial_bytes* contains optional initial :class:`bytes` data.
Georg Brandl014197c2008-04-09 18:40:51 +0000508
509 :class:`BytesIO` provides or overrides these methods in addition to those
510 from :class:`BufferedIOBase` and :class:`IOBase`:
511
Antoine Pitrou972ee132010-09-06 18:48:21 +0000512 .. method:: getbuffer()
513
514 Return a readable and writable view over the contents of the buffer
515 without copying them. Also, mutating the view will transparently
516 update the contents of the buffer::
517
518 >>> b = io.BytesIO(b"abcdef")
519 >>> view = b.getbuffer()
520 >>> view[2:4] = b"56"
521 >>> b.getvalue()
522 b'ab56ef'
523
524 .. note::
525 As long as the view exists, the :class:`BytesIO` object cannot be
526 resized.
527
528 .. versionadded:: 3.2
529
Georg Brandl014197c2008-04-09 18:40:51 +0000530 .. method:: getvalue()
531
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000532 Return ``bytes`` containing the entire contents of the buffer.
Georg Brandl014197c2008-04-09 18:40:51 +0000533
534 .. method:: read1()
535
Benjamin Peterson9efcc4b2008-04-14 21:30:21 +0000536 In :class:`BytesIO`, this is the same as :meth:`read`.
Georg Brandl014197c2008-04-09 18:40:51 +0000537
Georg Brandl014197c2008-04-09 18:40:51 +0000538
Georg Brandl3dd33882009-06-01 17:35:27 +0000539.. class:: BufferedReader(raw, buffer_size=DEFAULT_BUFFER_SIZE)
Georg Brandl014197c2008-04-09 18:40:51 +0000540
Antoine Pitrou497a7672009-09-17 17:18:01 +0000541 A buffer providing higher-level access to a readable, sequential
542 :class:`RawIOBase` object. It inherits :class:`BufferedIOBase`.
543 When reading data from this object, a larger amount of data may be
544 requested from the underlying raw stream, and kept in an internal buffer.
545 The buffered data can then be returned directly on subsequent reads.
Georg Brandl014197c2008-04-09 18:40:51 +0000546
547 The constructor creates a :class:`BufferedReader` for the given readable
548 *raw* stream and *buffer_size*. If *buffer_size* is omitted,
549 :data:`DEFAULT_BUFFER_SIZE` is used.
550
551 :class:`BufferedReader` provides or overrides these methods in addition to
552 those from :class:`BufferedIOBase` and :class:`IOBase`:
553
554 .. method:: peek([n])
555
Benjamin Petersonc43a26d2009-06-16 23:09:24 +0000556 Return bytes from the stream without advancing the position. At most one
Benjamin Peterson2a8b54d2009-06-14 14:37:23 +0000557 single read on the raw stream is done to satisfy the call. The number of
558 bytes returned may be less or more than requested.
Georg Brandl014197c2008-04-09 18:40:51 +0000559
560 .. method:: read([n])
561
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000562 Read and return *n* bytes, or if *n* is not given or negative, until EOF
Georg Brandl014197c2008-04-09 18:40:51 +0000563 or if the read call would block in non-blocking mode.
564
565 .. method:: read1(n)
566
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000567 Read and return up to *n* bytes with only one call on the raw stream. If
Georg Brandl014197c2008-04-09 18:40:51 +0000568 at least one byte is buffered, only buffered bytes are returned.
569 Otherwise, one raw stream read call is made.
570
571
Georg Brandl3dd33882009-06-01 17:35:27 +0000572.. class:: BufferedWriter(raw, buffer_size=DEFAULT_BUFFER_SIZE)
Georg Brandl014197c2008-04-09 18:40:51 +0000573
Antoine Pitrou497a7672009-09-17 17:18:01 +0000574 A buffer providing higher-level access to a writeable, sequential
575 :class:`RawIOBase` object. It inherits :class:`BufferedIOBase`.
576 When writing to this object, data is normally held into an internal
577 buffer. The buffer will be written out to the underlying :class:`RawIOBase`
578 object under various conditions, including:
579
580 * when the buffer gets too small for all pending data;
581 * when :meth:`flush()` is called;
582 * when a :meth:`seek()` is requested (for :class:`BufferedRandom` objects);
583 * when the :class:`BufferedWriter` object is closed or destroyed.
Georg Brandl014197c2008-04-09 18:40:51 +0000584
585 The constructor creates a :class:`BufferedWriter` for the given writeable
586 *raw* stream. If the *buffer_size* is not given, it defaults to
Benjamin Peterson394ee002009-03-05 22:33:59 +0000587 :data:`DEFAULT_BUFFER_SIZE`.
588
Georg Brandl3dd33882009-06-01 17:35:27 +0000589 A third argument, *max_buffer_size*, is supported, but unused and deprecated.
Georg Brandl014197c2008-04-09 18:40:51 +0000590
591 :class:`BufferedWriter` provides or overrides these methods in addition to
592 those from :class:`BufferedIOBase` and :class:`IOBase`:
593
594 .. method:: flush()
595
596 Force bytes held in the buffer into the raw stream. A
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000597 :exc:`BlockingIOError` should be raised if the raw stream blocks.
Georg Brandl014197c2008-04-09 18:40:51 +0000598
599 .. method:: write(b)
600
Antoine Pitrou497a7672009-09-17 17:18:01 +0000601 Write the bytes or bytearray object, *b* and return the number of bytes
602 written. When in non-blocking mode, a :exc:`BlockingIOError` is raised
603 if the buffer needs to be written out but the raw stream blocks.
Georg Brandl014197c2008-04-09 18:40:51 +0000604
605
Georg Brandl3dd33882009-06-01 17:35:27 +0000606.. class:: BufferedRandom(raw, buffer_size=DEFAULT_BUFFER_SIZE)
Georg Brandl014197c2008-04-09 18:40:51 +0000607
608 A buffered interface to random access streams. It inherits
Antoine Pitrou497a7672009-09-17 17:18:01 +0000609 :class:`BufferedReader` and :class:`BufferedWriter`, and further supports
610 :meth:`seek` and :meth:`tell` functionality.
Georg Brandl014197c2008-04-09 18:40:51 +0000611
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000612 The constructor creates a reader and writer for a seekable raw stream, given
Georg Brandl014197c2008-04-09 18:40:51 +0000613 in the first argument. If the *buffer_size* is omitted it defaults to
Benjamin Peterson394ee002009-03-05 22:33:59 +0000614 :data:`DEFAULT_BUFFER_SIZE`.
615
Georg Brandl3dd33882009-06-01 17:35:27 +0000616 A third argument, *max_buffer_size*, is supported, but unused and deprecated.
Georg Brandl014197c2008-04-09 18:40:51 +0000617
618 :class:`BufferedRandom` is capable of anything :class:`BufferedReader` or
619 :class:`BufferedWriter` can do.
620
621
Antoine Pitrou13d28952011-08-20 19:48:43 +0200622.. class:: BufferedRWPair(reader, writer, buffer_size=DEFAULT_BUFFER_SIZE)
623
624 A buffered I/O object combining two unidirectional :class:`RawIOBase`
625 objects -- one readable, the other writeable -- into a single bidirectional
626 endpoint. It inherits :class:`BufferedIOBase`.
627
628 *reader* and *writer* are :class:`RawIOBase` objects that are readable and
629 writeable respectively. If the *buffer_size* is omitted it defaults to
630 :data:`DEFAULT_BUFFER_SIZE`.
631
632 A fourth argument, *max_buffer_size*, is supported, but unused and
633 deprecated.
634
635 :class:`BufferedRWPair` implements all of :class:`BufferedIOBase`\'s methods
636 except for :meth:`~BufferedIOBase.detach`, which raises
637 :exc:`UnsupportedOperation`.
638
639 .. warning::
640 :class:`BufferedRWPair` does not attempt to synchronize accesses to
641 its underlying raw streams. You should not pass it the same object
642 as reader and writer; use :class:`BufferedRandom` instead.
643
644
Georg Brandl014197c2008-04-09 18:40:51 +0000645Text I/O
Antoine Pitroub530e142010-08-30 12:41:00 +0000646^^^^^^^^
Georg Brandl014197c2008-04-09 18:40:51 +0000647
648.. class:: TextIOBase
649
650 Base class for text streams. This class provides a character and line based
651 interface to stream I/O. There is no :meth:`readinto` method because
652 Python's character strings are immutable. It inherits :class:`IOBase`.
653 There is no public constructor.
654
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000655 :class:`TextIOBase` provides or overrides these data attributes and
656 methods in addition to those from :class:`IOBase`:
Georg Brandl014197c2008-04-09 18:40:51 +0000657
658 .. attribute:: encoding
659
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000660 The name of the encoding used to decode the stream's bytes into
Georg Brandl014197c2008-04-09 18:40:51 +0000661 strings, and to encode strings into bytes.
662
Benjamin Peterson0926ad12009-06-06 18:02:12 +0000663 .. attribute:: errors
664
665 The error setting of the decoder or encoder.
666
Georg Brandl014197c2008-04-09 18:40:51 +0000667 .. attribute:: newlines
668
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000669 A string, a tuple of strings, or ``None``, indicating the newlines
Antoine Pitrou497a7672009-09-17 17:18:01 +0000670 translated so far. Depending on the implementation and the initial
671 constructor flags, this may not be available.
Georg Brandl014197c2008-04-09 18:40:51 +0000672
Benjamin Petersonc609b6b2009-06-28 17:32:20 +0000673 .. attribute:: buffer
674
675 The underlying binary buffer (a :class:`BufferedIOBase` instance) that
676 :class:`TextIOBase` deals with. This is not part of the
677 :class:`TextIOBase` API and may not exist on some implementations.
678
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000679 .. method:: detach()
680
Antoine Pitrou497a7672009-09-17 17:18:01 +0000681 Separate the underlying binary buffer from the :class:`TextIOBase` and
682 return it.
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000683
684 After the underlying buffer has been detached, the :class:`TextIOBase` is
685 in an unusable state.
686
687 Some :class:`TextIOBase` implementations, like :class:`StringIO`, may not
688 have the concept of an underlying buffer and calling this method will
689 raise :exc:`UnsupportedOperation`.
690
Benjamin Petersonedc36472009-05-01 20:48:14 +0000691 .. versionadded:: 3.1
692
Georg Brandl014197c2008-04-09 18:40:51 +0000693 .. method:: read(n)
694
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000695 Read and return at most *n* characters from the stream as a single
Antoine Pitrou497a7672009-09-17 17:18:01 +0000696 :class:`str`. If *n* is negative or ``None``, reads until EOF.
Georg Brandl014197c2008-04-09 18:40:51 +0000697
698 .. method:: readline()
699
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000700 Read until newline or EOF and return a single ``str``. If the stream is
701 already at EOF, an empty string is returned.
Georg Brandl014197c2008-04-09 18:40:51 +0000702
Georg Brandl014197c2008-04-09 18:40:51 +0000703 .. method:: write(s)
704
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000705 Write the string *s* to the stream and return the number of characters
706 written.
Georg Brandl014197c2008-04-09 18:40:51 +0000707
708
Antoine Pitrou664091b2011-07-23 22:00:03 +0200709.. class:: TextIOWrapper(buffer, encoding=None, errors=None, newline=None, \
710 line_buffering=False, write_through=False)
Georg Brandl014197c2008-04-09 18:40:51 +0000711
Antoine Pitrou497a7672009-09-17 17:18:01 +0000712 A buffered text stream over a :class:`BufferedIOBase` binary stream.
Georg Brandl014197c2008-04-09 18:40:51 +0000713 It inherits :class:`TextIOBase`.
714
715 *encoding* gives the name of the encoding that the stream will be decoded or
716 encoded with. It defaults to :func:`locale.getpreferredencoding`.
717
Benjamin Petersonb85a5842008-04-13 21:39:58 +0000718 *errors* is an optional string that specifies how encoding and decoding
719 errors are to be handled. Pass ``'strict'`` to raise a :exc:`ValueError`
720 exception if there is an encoding error (the default of ``None`` has the same
721 effect), or pass ``'ignore'`` to ignore errors. (Note that ignoring encoding
722 errors can lead to data loss.) ``'replace'`` causes a replacement marker
Christian Heimesa342c012008-04-20 21:01:16 +0000723 (such as ``'?'``) to be inserted where there is malformed data. When
724 writing, ``'xmlcharrefreplace'`` (replace with the appropriate XML character
725 reference) or ``'backslashreplace'`` (replace with backslashed escape
726 sequences) can be used. Any other error handling name that has been
727 registered with :func:`codecs.register_error` is also valid.
Georg Brandl014197c2008-04-09 18:40:51 +0000728
729 *newline* can be ``None``, ``''``, ``'\n'``, ``'\r'``, or ``'\r\n'``. It
730 controls the handling of line endings. If it is ``None``, universal newlines
731 is enabled. With this enabled, on input, the lines endings ``'\n'``,
732 ``'\r'``, or ``'\r\n'`` are translated to ``'\n'`` before being returned to
733 the caller. Conversely, on output, ``'\n'`` is translated to the system
Mark Dickinson934896d2009-02-21 20:59:32 +0000734 default line separator, :data:`os.linesep`. If *newline* is any other of its
Georg Brandl014197c2008-04-09 18:40:51 +0000735 legal values, that newline becomes the newline when the file is read and it
736 is returned untranslated. On output, ``'\n'`` is converted to the *newline*.
737
738 If *line_buffering* is ``True``, :meth:`flush` is implied when a call to
739 write contains a newline character.
740
Antoine Pitrou664091b2011-07-23 22:00:03 +0200741 If *write_through* is ``True``, calls to :meth:`write` are guaranteed
742 not to be buffered: any data written on the :class:`TextIOWrapper`
743 object is immediately handled to its underlying binary *buffer*.
744
745 .. versionchanged:: 3.3
746 The *write_through* argument has been added.
747
Benjamin Peterson0926ad12009-06-06 18:02:12 +0000748 :class:`TextIOWrapper` provides one attribute in addition to those of
Georg Brandl014197c2008-04-09 18:40:51 +0000749 :class:`TextIOBase` and its parents:
750
Georg Brandl014197c2008-04-09 18:40:51 +0000751 .. attribute:: line_buffering
752
753 Whether line buffering is enabled.
Georg Brandl48310cd2009-01-03 21:18:54 +0000754
Georg Brandl014197c2008-04-09 18:40:51 +0000755
Georg Brandl3dd33882009-06-01 17:35:27 +0000756.. class:: StringIO(initial_value='', newline=None)
Georg Brandl014197c2008-04-09 18:40:51 +0000757
Antoine Pitroub530e142010-08-30 12:41:00 +0000758 An in-memory stream for text I/O.
Georg Brandl014197c2008-04-09 18:40:51 +0000759
Benjamin Petersonaa1c8d82009-03-09 02:02:23 +0000760 The initial value of the buffer (an empty string by default) can be set by
761 providing *initial_value*. The *newline* argument works like that of
762 :class:`TextIOWrapper`. The default is to do no newline translation.
Georg Brandl014197c2008-04-09 18:40:51 +0000763
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000764 :class:`StringIO` provides this method in addition to those from
Antoine Pitroub530e142010-08-30 12:41:00 +0000765 :class:`TextIOBase` and its parents:
Georg Brandl014197c2008-04-09 18:40:51 +0000766
767 .. method:: getvalue()
768
Georg Brandl2932d932008-05-30 06:27:09 +0000769 Return a ``str`` containing the entire contents of the buffer at any
770 time before the :class:`StringIO` object's :meth:`close` method is
771 called.
Georg Brandl014197c2008-04-09 18:40:51 +0000772
Georg Brandl2932d932008-05-30 06:27:09 +0000773 Example usage::
774
775 import io
776
777 output = io.StringIO()
778 output.write('First line.\n')
779 print('Second line.', file=output)
780
781 # Retrieve file contents -- this will be
782 # 'First line.\nSecond line.\n'
783 contents = output.getvalue()
784
Georg Brandl48310cd2009-01-03 21:18:54 +0000785 # Close object and discard memory buffer --
Georg Brandl2932d932008-05-30 06:27:09 +0000786 # .getvalue() will now raise an exception.
787 output.close()
Georg Brandl014197c2008-04-09 18:40:51 +0000788
Antoine Pitroub530e142010-08-30 12:41:00 +0000789
Georg Brandl014197c2008-04-09 18:40:51 +0000790.. class:: IncrementalNewlineDecoder
791
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000792 A helper codec that decodes newlines for universal newlines mode. It
793 inherits :class:`codecs.IncrementalDecoder`.
Georg Brandl014197c2008-04-09 18:40:51 +0000794
Antoine Pitroubed81c82010-12-03 19:14:17 +0000795
Antoine Pitroubed81c82010-12-03 19:14:17 +0000796Performance
Benjamin Petersonedf51322011-02-24 03:03:46 +0000797-----------
798
799This section discusses the performance of the provided concrete I/O
800implementations.
Antoine Pitroubed81c82010-12-03 19:14:17 +0000801
802Binary I/O
Benjamin Petersonedf51322011-02-24 03:03:46 +0000803^^^^^^^^^^
Antoine Pitroubed81c82010-12-03 19:14:17 +0000804
Benjamin Petersonedf51322011-02-24 03:03:46 +0000805By reading and writing only large chunks of data even when the user asks for a
806single byte, buffered I/O hides any inefficiency in calling and executing the
807operating system's unbuffered I/O routines. The gain depends on the OS and the
808kind of I/O which is performed. For example, on some modern OSes such as Linux,
809unbuffered disk I/O can be as fast as buffered I/O. The bottom line, however,
810is that buffered I/O offers predictable performance regardless of the platform
811and the backing device. Therefore, it is most always preferable to use buffered
812I/O rather than unbuffered I/O for binary datal
Antoine Pitroubed81c82010-12-03 19:14:17 +0000813
814Text I/O
Benjamin Petersonedf51322011-02-24 03:03:46 +0000815^^^^^^^^
Antoine Pitroubed81c82010-12-03 19:14:17 +0000816
817Text I/O over a binary storage (such as a file) is significantly slower than
Benjamin Petersonedf51322011-02-24 03:03:46 +0000818binary I/O over the same storage, because it requires conversions between
819unicode and binary data using a character codec. This can become noticeable
820handling huge amounts of text data like large log files. Also,
821:meth:`TextIOWrapper.tell` and :meth:`TextIOWrapper.seek` are both quite slow
822due to the reconstruction algorithm used.
Antoine Pitroubed81c82010-12-03 19:14:17 +0000823
824:class:`StringIO`, however, is a native in-memory unicode container and will
825exhibit similar speed to :class:`BytesIO`.
826
827Multi-threading
828^^^^^^^^^^^^^^^
829
Benjamin Petersonedf51322011-02-24 03:03:46 +0000830:class:`FileIO` objects are thread-safe to the extent that the operating system
831calls (such as ``read(2)`` under Unix) they wrap are thread-safe too.
Antoine Pitroubed81c82010-12-03 19:14:17 +0000832
833Binary buffered objects (instances of :class:`BufferedReader`,
834:class:`BufferedWriter`, :class:`BufferedRandom` and :class:`BufferedRWPair`)
835protect their internal structures using a lock; it is therefore safe to call
836them from multiple threads at once.
837
838:class:`TextIOWrapper` objects are not thread-safe.
839
840Reentrancy
841^^^^^^^^^^
842
843Binary buffered objects (instances of :class:`BufferedReader`,
844:class:`BufferedWriter`, :class:`BufferedRandom` and :class:`BufferedRWPair`)
845are not reentrant. While reentrant calls will not happen in normal situations,
Benjamin Petersonedf51322011-02-24 03:03:46 +0000846they can arise from doing I/O in a :mod:`signal` handler. If a thread tries to
847renter a buffered object which it is already accessing, a :exc:`RuntimeError` is
848raised. Note this doesn't prohibit a different thread from entering the
849buffered object.
Antoine Pitroubed81c82010-12-03 19:14:17 +0000850
Benjamin Petersonedf51322011-02-24 03:03:46 +0000851The above implicitly extends to text files, since the :func:`open()` function
852will wrap a buffered object inside a :class:`TextIOWrapper`. This includes
853standard streams and therefore affects the built-in function :func:`print()` as
854well.
Antoine Pitroubed81c82010-12-03 19:14:17 +0000855