Merged revisions 84359-84360 via svnmerge from
[python/dscho.git] / Doc / library / io.rst
blobb2e586aa0f57ae27b1894ff7ac92ac275317b2d4
1 :mod:`io` --- Core tools for working with streams
2 =================================================
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>
9 .. moduleauthor:: Antoine Pitrou <solipsis@pitrou.net>
10 .. moduleauthor:: Amaury Forgeot d'Arc <amauryfa@gmail.com>
11 .. moduleauthor:: Benjamin Peterson <benjamin@python.org>
12 .. sectionauthor:: Benjamin Peterson <benjamin@python.org>
14 .. _io-overview:
16 Overview
17 --------
19 The :mod:`io` module provides Python's main facilities for dealing for various
20 types of I/O.  There are three main types of I/O: *text I/O*, *binary I/O*, *raw
21 I/O*.  These are generic categories, and various backing stores can be used for
22 each of them.  Concrete objects belonging to any of these categories will often
23 be called *streams*; another common term is *file-like objects*.
25 Independently of its category, each concrete stream object will also have
26 various capabilities: it can be read-only, write-only, or read-write. It can
27 also allow arbitrary random access (seeking forwards or backwards to any
28 location), or only sequential access (for example in the case of a socket or
29 pipe).
31 All streams are careful about the type of data you give to them.  For example
32 giving a :class:`str` object to the ``write()`` method of a binary stream
33 will raise a ``TypeError``.  So will giving a :class:`bytes` object to the
34 ``write()`` method of a text stream.
37 Text I/O
38 ^^^^^^^^
40 Text I/O expects and produces :class:`str` objects.  This means that whenever
41 the backing store is natively made of bytes (such as in the case of a file),
42 encoding and decoding of data is made transparently as well as optional
43 translation of platform-specific newline characters.
45 The easiest way to create a text stream is with :meth:`open()`, optionally
46 specifying an encoding::
48    f = open("myfile.txt", "r", encoding="utf-8")
50 In-memory text streams are also available as :class:`StringIO` objects::
52    f = io.StringIO("some initial text data")
54 The text stream API is described in detail in the documentation for the
55 :class:`TextIOBase`.
57 .. note::
59    Text I/O over a binary storage (such as a file) is significantly slower than
60    binary I/O over the same storage.  This can become noticeable if you handle
61    huge amounts of text data (for example very large log files).
64 Binary I/O
65 ^^^^^^^^^^
67 Binary I/O (also called *buffered I/O*) expects and produces :class:`bytes`
68 objects.  No encoding, decoding, or newline translation is performed.  This
69 category of streams can be used for all kinds of non-text data, and also when
70 manual control over the handling of text data is desired.
72 The easiest way to create a binary stream is with :meth:`open()` with ``'b'`` in
73 the mode string::
75    f = open("myfile.jpg", "rb")
77 In-memory binary streams are also available as :class:`BytesIO` objects::
79    f = io.BytesIO(b"some initial binary data: \x00\x01")
81 The binary stream API is described in detail in the docs of
82 :class:`BufferedIOBase`.
84 Other library modules may provide additional ways to create text or binary
85 streams.  See :meth:`socket.socket.makefile` for example.
88 Raw I/O
89 ^^^^^^^
91 Raw I/O (also called *unbuffered I/O*) is generally used as a low-level
92 building-block for binary and text streams; it is rarely useful to directly
93 manipulate a raw stream from user code.  Nevertheless, you can create a raw
94 stream by opening a file in binary mode with buffering disabled::
96    f = open("myfile.jpg", "rb", buffering=0)
98 The raw stream API is described in detail in the docs of :class:`RawIOBase`.
101 High-level Module Interface
102 ---------------------------
104 .. data:: DEFAULT_BUFFER_SIZE
106    An int containing the default buffer size used by the module's buffered I/O
107    classes.  :func:`open` uses the file's blksize (as obtained by
108    :func:`os.stat`) if possible.
111 .. function:: open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True)
113    This is an alias for the builtin :func:`open` function.
116 .. exception:: BlockingIOError
118    Error raised when blocking would occur on a non-blocking stream.  It inherits
119    :exc:`IOError`.
121    In addition to those of :exc:`IOError`, :exc:`BlockingIOError` has one
122    attribute:
124    .. attribute:: characters_written
126       An integer containing the number of characters written to the stream
127       before it blocked.
130 .. exception:: UnsupportedOperation
132    An exception inheriting :exc:`IOError` and :exc:`ValueError` that is raised
133    when an unsupported operation is called on a stream.
136 In-memory streams
137 ^^^^^^^^^^^^^^^^^
139 It is also possible to use a :class:`str` or :class:`bytes`-like object as a
140 file for both reading and writing.  For strings :class:`StringIO` can be used
141 like a file opened in text mode.  :class:`BytesIO` can be used like a file
142 opened in binary mode.  Both provide full read-write capabilities with random
143 access.
146 .. seealso::
148    :mod:`sys`
149        contains the standard IO streams: :data:`sys.stdin`, :data:`sys.stdout`,
150        and :data:`sys.stderr`.
153 Class hierarchy
154 ---------------
156 The implementation of I/O streams is organized as a hierarchy of classes.  First
157 :term:`abstract base classes <abstract base class>` (ABCs), which are used to
158 specify the various categories of streams, then concrete classes providing the
159 standard stream implementations.
161    .. note::
163       The abstract base classes also provide default implementations of some
164       methods in order to help implementation of concrete stream classes.  For
165       example, :class:`BufferedIOBase` provides unoptimized implementations of
166       ``readinto()`` and ``readline()``.
168 At the top of the I/O hierarchy is the abstract base class :class:`IOBase`.  It
169 defines the basic interface to a stream.  Note, however, that there is no
170 separation between reading and writing to streams; implementations are allowed
171 to raise :exc:`UnsupportedOperation` if they do not support a given operation.
173 The :class:`RawIOBase` ABC extends :class:`IOBase`.  It deals with the reading
174 and writing of bytes to a stream.  :class:`FileIO` subclasses :class:`RawIOBase`
175 to provide an interface to files in the machine's file system.
177 The :class:`BufferedIOBase` ABC deals with buffering on a raw byte stream
178 (:class:`RawIOBase`).  Its subclasses, :class:`BufferedWriter`,
179 :class:`BufferedReader`, and :class:`BufferedRWPair` buffer streams that are
180 readable, writable, and both readable and writable.  :class:`BufferedRandom`
181 provides a buffered interface to random access streams.  Another
182 :class`BufferedIOBase` subclass, :class:`BytesIO`, is a stream of in-memory
183 bytes.
185 The :class:`TextIOBase` ABC, another subclass of :class:`IOBase`, deals with
186 streams whose bytes represent text, and handles encoding and decoding to and
187 from strings. :class:`TextIOWrapper`, which extends it, is a buffered text
188 interface to a buffered raw stream (:class:`BufferedIOBase`). Finally,
189 :class:`StringIO` is an in-memory stream for text.
191 Argument names are not part of the specification, and only the arguments of
192 :func:`open` are intended to be used as keyword arguments.
195 I/O Base Classes
196 ^^^^^^^^^^^^^^^^
198 .. class:: IOBase
200    The abstract base class for all I/O classes, acting on streams of bytes.
201    There is no public constructor.
203    This class provides empty abstract implementations for many methods
204    that derived classes can override selectively; the default
205    implementations represent a file that cannot be read, written or
206    seeked.
208    Even though :class:`IOBase` does not declare :meth:`read`, :meth:`readinto`,
209    or :meth:`write` because their signatures will vary, implementations and
210    clients should consider those methods part of the interface.  Also,
211    implementations may raise a :exc:`IOError` when operations they do not
212    support are called.
214    The basic type used for binary data read from or written to a file is
215    :class:`bytes`.  :class:`bytearray`\s are accepted too, and in some cases
216    (such as :class:`readinto`) required.  Text I/O classes work with
217    :class:`str` data.
219    Note that calling any method (even inquiries) on a closed stream is
220    undefined.  Implementations may raise :exc:`IOError` in this case.
222    IOBase (and its subclasses) support the iterator protocol, meaning that an
223    :class:`IOBase` object can be iterated over yielding the lines in a stream.
224    Lines are defined slightly differently depending on whether the stream is
225    a binary stream (yielding bytes), or a text stream (yielding character
226    strings).  See :meth:`readline` below.
228    IOBase is also a context manager and therefore supports the
229    :keyword:`with` statement.  In this example, *file* is closed after the
230    :keyword:`with` statement's suite is finished---even if an exception occurs::
232       with open('spam.txt', 'w') as file:
233           file.write('Spam and eggs!')
235    :class:`IOBase` provides these data attributes and methods:
237    .. method:: close()
239       Flush and close this stream. This method has no effect if the file is
240       already closed. Once the file is closed, any operation on the file
241       (e.g. reading or writing) will raise a :exc:`ValueError`.
243       As a convenience, it is allowed to call this method more than once;
244       only the first call, however, will have an effect.
246    .. attribute:: closed
248       True if the stream is closed.
250    .. method:: fileno()
252       Return the underlying file descriptor (an integer) of the stream if it
253       exists.  An :exc:`IOError` is raised if the IO object does not use a file
254       descriptor.
256    .. method:: flush()
258       Flush the write buffers of the stream if applicable.  This does nothing
259       for read-only and non-blocking streams.
261    .. method:: isatty()
263       Return ``True`` if the stream is interactive (i.e., connected to
264       a terminal/tty device).
266    .. method:: readable()
268       Return ``True`` if the stream can be read from.  If False, :meth:`read`
269       will raise :exc:`IOError`.
271    .. method:: readline(limit=-1)
273       Read and return one line from the stream.  If *limit* is specified, at
274       most *limit* bytes will be read.
276       The line terminator is always ``b'\n'`` for binary files; for text files,
277       the *newlines* argument to :func:`open` can be used to select the line
278       terminator(s) recognized.
280    .. method:: readlines(hint=-1)
282       Read and return a list of lines from the stream.  *hint* can be specified
283       to control the number of lines read: no more lines will be read if the
284       total size (in bytes/characters) of all lines so far exceeds *hint*.
286    .. method:: seek(offset, whence=SEEK_SET)
288       Change the stream position to the given byte *offset*.  *offset* is
289       interpreted relative to the position indicated by *whence*.  Values for
290       *whence* are:
292       * :data:`SEEK_SET` or ``0`` -- start of the stream (the default);
293         *offset* should be zero or positive
294       * :data:`SEEK_CUR` or ``1`` -- current stream position; *offset* may
295         be negative
296       * :data:`SEEK_END` or ``2`` -- end of the stream; *offset* is usually
297         negative
299       Return the new absolute position.
301       .. versionadded:: 3.1
302          The ``SEEK_*`` constants
304    .. method:: seekable()
306       Return ``True`` if the stream supports random access.  If ``False``,
307       :meth:`seek`, :meth:`tell` and :meth:`truncate` will raise :exc:`IOError`.
309    .. method:: tell()
311       Return the current stream position.
313    .. method:: truncate(size=None)
315       Resize the stream to the given *size* in bytes (or the current position
316       if *size* is not specified).  The current stream position isn't changed.
317       This resizing can extend or reduce the current file size.  In case of
318       extension, the contents of the new file area depend on the platform
319       (on most systems, additional bytes are zero-filled, on Windows they're
320       undetermined).  The new file size is returned.
322    .. method:: writable()
324       Return ``True`` if the stream supports writing.  If ``False``,
325       :meth:`write` and :meth:`truncate` will raise :exc:`IOError`.
327    .. method:: writelines(lines)
329       Write a list of lines to the stream.  Line separators are not added, so it
330       is usual for each of the lines provided to have a line separator at the
331       end.
334 .. class:: RawIOBase
336    Base class for raw binary I/O.  It inherits :class:`IOBase`.  There is no
337    public constructor.
339    Raw binary I/O typically provides low-level access to an underlying OS
340    device or API, and does not try to encapsulate it in high-level primitives
341    (this is left to Buffered I/O and Text I/O, described later in this page).
343    In addition to the attributes and methods from :class:`IOBase`,
344    RawIOBase provides the following methods:
346    .. method:: read(n=-1)
348       Read up to *n* bytes from the object and return them.  As a convenience,
349       if *n* is unspecified or -1, :meth:`readall` is called.  Otherwise,
350       only one system call is ever made.  Fewer than *n* bytes may be
351       returned if the operating system call returns fewer than *n* bytes.
353       If 0 bytes are returned, and *n* was not 0, this indicates end of file.
354       If the object is in non-blocking mode and no bytes are available,
355       ``None`` is returned.
357    .. method:: readall()
359       Read and return all the bytes from the stream until EOF, using multiple
360       calls to the stream if necessary.
362    .. method:: readinto(b)
364       Read up to len(b) bytes into bytearray *b* and return the number of bytes
365       read.
367    .. method:: write(b)
369       Write the given bytes or bytearray object, *b*, to the underlying raw
370       stream and return the number of bytes written.  This can be less than
371       ``len(b)``, depending on specifics of the underlying raw stream, and
372       especially if it is in non-blocking mode.  ``None`` is returned if the
373       raw stream is set not to block and no single byte could be readily
374       written to it.
377 .. class:: BufferedIOBase
379    Base class for binary streams that support some kind of buffering.
380    It inherits :class:`IOBase`. There is no public constructor.
382    The main difference with :class:`RawIOBase` is that methods :meth:`read`,
383    :meth:`readinto` and :meth:`write` will try (respectively) to read as much
384    input as requested or to consume all given output, at the expense of
385    making perhaps more than one system call.
387    In addition, those methods can raise :exc:`BlockingIOError` if the
388    underlying raw stream is in non-blocking mode and cannot take or give
389    enough data; unlike their :class:`RawIOBase` counterparts, they will
390    never return ``None``.
392    Besides, the :meth:`read` method does not have a default
393    implementation that defers to :meth:`readinto`.
395    A typical :class:`BufferedIOBase` implementation should not inherit from a
396    :class:`RawIOBase` implementation, but wrap one, like
397    :class:`BufferedWriter` and :class:`BufferedReader` do.
399    :class:`BufferedIOBase` provides or overrides these members in addition to
400    those from :class:`IOBase`:
402    .. attribute:: raw
404       The underlying raw stream (a :class:`RawIOBase` instance) that
405       :class:`BufferedIOBase` deals with.  This is not part of the
406       :class:`BufferedIOBase` API and may not exist on some implementations.
408    .. method:: detach()
410       Separate the underlying raw stream from the buffer and return it.
412       After the raw stream has been detached, the buffer is in an unusable
413       state.
415       Some buffers, like :class:`BytesIO`, do not have the concept of a single
416       raw stream to return from this method.  They raise
417       :exc:`UnsupportedOperation`.
419       .. versionadded:: 3.1
421    .. method:: read(n=-1)
423       Read and return up to *n* bytes.  If the argument is omitted, ``None``, or
424       negative, data is read and returned until EOF is reached.  An empty bytes
425       object is returned if the stream is already at EOF.
427       If the argument is positive, and the underlying raw stream is not
428       interactive, multiple raw reads may be issued to satisfy the byte count
429       (unless EOF is reached first).  But for interactive raw streams, at most
430       one raw read will be issued, and a short result does not imply that EOF is
431       imminent.
433       A :exc:`BlockingIOError` is raised if the underlying raw stream is in
434       non blocking-mode, and has no data available at the moment.
436    .. method:: read1(n=-1)
438       Read and return up to *n* bytes, with at most one call to the underlying
439       raw stream's :meth:`~RawIOBase.read` method.  This can be useful if you
440       are implementing your own buffering on top of a :class:`BufferedIOBase`
441       object.
443    .. method:: readinto(b)
445       Read up to len(b) bytes into bytearray *b* and return the number of bytes
446       read.
448       Like :meth:`read`, multiple reads may be issued to the underlying raw
449       stream, unless the latter is 'interactive'.
451       A :exc:`BlockingIOError` is raised if the underlying raw stream is in
452       non blocking-mode, and has no data available at the moment.
454    .. method:: write(b)
456       Write the given bytes or bytearray object, *b* and return the number
457       of bytes written (never less than ``len(b)``, since if the write fails
458       an :exc:`IOError` will be raised).  Depending on the actual
459       implementation, these bytes may be readily written to the underlying
460       stream, or held in a buffer for performance and latency reasons.
462       When in non-blocking mode, a :exc:`BlockingIOError` is raised if the
463       data needed to be written to the raw stream but it couldn't accept
464       all the data without blocking.
467 Raw File I/O
468 ^^^^^^^^^^^^
470 .. class:: FileIO(name, mode='r', closefd=True)
472    :class:`FileIO` represents an OS-level file containing bytes data.
473    It implements the :class:`RawIOBase` interface (and therefore the
474    :class:`IOBase` interface, too).
476    The *name* can be one of two things:
478    * a character string or bytes object representing the path to the file
479      which will be opened;
480    * an integer representing the number of an existing OS-level file descriptor
481      to which the resulting :class:`FileIO` object will give access.
483    The *mode* can be ``'r'``, ``'w'`` or ``'a'`` for reading (default), writing,
484    or appending.  The file will be created if it doesn't exist when opened for
485    writing or appending; it will be truncated when opened for writing.  Add a
486    ``'+'`` to the mode to allow simultaneous reading and writing.
488    The :meth:`read` (when called with a positive argument), :meth:`readinto`
489    and :meth:`write` methods on this class will only make one system call.
491    In addition to the attributes and methods from :class:`IOBase` and
492    :class:`RawIOBase`, :class:`FileIO` provides the following data
493    attributes and methods:
495    .. attribute:: mode
497       The mode as given in the constructor.
499    .. attribute:: name
501       The file name.  This is the file descriptor of the file when no name is
502       given in the constructor.
505 Buffered Streams
506 ^^^^^^^^^^^^^^^^
508 In many situations, buffered I/O streams will provide higher performance
509 (bandwidth and latency) than raw I/O streams.  Their API is also more usable.
511 .. class:: BytesIO([initial_bytes])
513    A stream implementation using an in-memory bytes buffer.  It inherits
514    :class:`BufferedIOBase`.
516    The argument *initial_bytes* contains optional initial :class:`bytes` data.
518    :class:`BytesIO` provides or overrides these methods in addition to those
519    from :class:`BufferedIOBase` and :class:`IOBase`:
521    .. method:: getvalue()
523       Return ``bytes`` containing the entire contents of the buffer.
525    .. method:: read1()
527       In :class:`BytesIO`, this is the same as :meth:`read`.
530 .. class:: BufferedReader(raw, buffer_size=DEFAULT_BUFFER_SIZE)
532    A buffer providing higher-level access to a readable, sequential
533    :class:`RawIOBase` object.  It inherits :class:`BufferedIOBase`.
534    When reading data from this object, a larger amount of data may be
535    requested from the underlying raw stream, and kept in an internal buffer.
536    The buffered data can then be returned directly on subsequent reads.
538    The constructor creates a :class:`BufferedReader` for the given readable
539    *raw* stream and *buffer_size*.  If *buffer_size* is omitted,
540    :data:`DEFAULT_BUFFER_SIZE` is used.
542    :class:`BufferedReader` provides or overrides these methods in addition to
543    those from :class:`BufferedIOBase` and :class:`IOBase`:
545    .. method:: peek([n])
547       Return bytes from the stream without advancing the position.  At most one
548       single read on the raw stream is done to satisfy the call. The number of
549       bytes returned may be less or more than requested.
551    .. method:: read([n])
553       Read and return *n* bytes, or if *n* is not given or negative, until EOF
554       or if the read call would block in non-blocking mode.
556    .. method:: read1(n)
558       Read and return up to *n* bytes with only one call on the raw stream.  If
559       at least one byte is buffered, only buffered bytes are returned.
560       Otherwise, one raw stream read call is made.
563 .. class:: BufferedWriter(raw, buffer_size=DEFAULT_BUFFER_SIZE)
565    A buffer providing higher-level access to a writeable, sequential
566    :class:`RawIOBase` object.  It inherits :class:`BufferedIOBase`.
567    When writing to this object, data is normally held into an internal
568    buffer.  The buffer will be written out to the underlying :class:`RawIOBase`
569    object under various conditions, including:
571    * when the buffer gets too small for all pending data;
572    * when :meth:`flush()` is called;
573    * when a :meth:`seek()` is requested (for :class:`BufferedRandom` objects);
574    * when the :class:`BufferedWriter` object is closed or destroyed.
576    The constructor creates a :class:`BufferedWriter` for the given writeable
577    *raw* stream.  If the *buffer_size* is not given, it defaults to
578    :data:`DEFAULT_BUFFER_SIZE`.
580    A third argument, *max_buffer_size*, is supported, but unused and deprecated.
582    :class:`BufferedWriter` provides or overrides these methods in addition to
583    those from :class:`BufferedIOBase` and :class:`IOBase`:
585    .. method:: flush()
587       Force bytes held in the buffer into the raw stream.  A
588       :exc:`BlockingIOError` should be raised if the raw stream blocks.
590    .. method:: write(b)
592       Write the bytes or bytearray object, *b* and return the number of bytes
593       written.  When in non-blocking mode, a :exc:`BlockingIOError` is raised
594       if the buffer needs to be written out but the raw stream blocks.
597 .. class:: BufferedRWPair(reader, writer, buffer_size=DEFAULT_BUFFER_SIZE)
599    A buffered I/O object giving a combined, higher-level access to two
600    sequential :class:`RawIOBase` objects: one readable, the other writeable.
601    It is useful for pairs of unidirectional communication channels
602    (pipes, for instance).  It inherits :class:`BufferedIOBase`.
604    *reader* and *writer* are :class:`RawIOBase` objects that are readable and
605    writeable respectively.  If the *buffer_size* is omitted it defaults to
606    :data:`DEFAULT_BUFFER_SIZE`.
608    A fourth argument, *max_buffer_size*, is supported, but unused and
609    deprecated.
611    :class:`BufferedRWPair` implements all of :class:`BufferedIOBase`\'s methods
612    except for :meth:`~BufferedIOBase.detach`, which raises
613    :exc:`UnsupportedOperation`.
616 .. class:: BufferedRandom(raw, buffer_size=DEFAULT_BUFFER_SIZE)
618    A buffered interface to random access streams.  It inherits
619    :class:`BufferedReader` and :class:`BufferedWriter`, and further supports
620    :meth:`seek` and :meth:`tell` functionality.
622    The constructor creates a reader and writer for a seekable raw stream, given
623    in the first argument.  If the *buffer_size* is omitted it defaults to
624    :data:`DEFAULT_BUFFER_SIZE`.
626    A third argument, *max_buffer_size*, is supported, but unused and deprecated.
628    :class:`BufferedRandom` is capable of anything :class:`BufferedReader` or
629    :class:`BufferedWriter` can do.
632 Text I/O
633 ^^^^^^^^
635 .. class:: TextIOBase
637    Base class for text streams.  This class provides a character and line based
638    interface to stream I/O.  There is no :meth:`readinto` method because
639    Python's character strings are immutable.  It inherits :class:`IOBase`.
640    There is no public constructor.
642    :class:`TextIOBase` provides or overrides these data attributes and
643    methods in addition to those from :class:`IOBase`:
645    .. attribute:: encoding
647       The name of the encoding used to decode the stream's bytes into
648       strings, and to encode strings into bytes.
650    .. attribute:: errors
652       The error setting of the decoder or encoder.
654    .. attribute:: newlines
656       A string, a tuple of strings, or ``None``, indicating the newlines
657       translated so far.  Depending on the implementation and the initial
658       constructor flags, this may not be available.
660    .. attribute:: buffer
662       The underlying binary buffer (a :class:`BufferedIOBase` instance) that
663       :class:`TextIOBase` deals with.  This is not part of the
664       :class:`TextIOBase` API and may not exist on some implementations.
666    .. method:: detach()
668       Separate the underlying binary buffer from the :class:`TextIOBase` and
669       return it.
671       After the underlying buffer has been detached, the :class:`TextIOBase` is
672       in an unusable state.
674       Some :class:`TextIOBase` implementations, like :class:`StringIO`, may not
675       have the concept of an underlying buffer and calling this method will
676       raise :exc:`UnsupportedOperation`.
678       .. versionadded:: 3.1
680    .. method:: read(n)
682       Read and return at most *n* characters from the stream as a single
683       :class:`str`.  If *n* is negative or ``None``, reads until EOF.
685    .. method:: readline()
687       Read until newline or EOF and return a single ``str``.  If the stream is
688       already at EOF, an empty string is returned.
690    .. method:: write(s)
692       Write the string *s* to the stream and return the number of characters
693       written.
696 .. class:: TextIOWrapper(buffer, encoding=None, errors=None, newline=None, line_buffering=False)
698    A buffered text stream over a :class:`BufferedIOBase` binary stream.
699    It inherits :class:`TextIOBase`.
701    *encoding* gives the name of the encoding that the stream will be decoded or
702    encoded with.  It defaults to :func:`locale.getpreferredencoding`.
704    *errors* is an optional string that specifies how encoding and decoding
705    errors are to be handled.  Pass ``'strict'`` to raise a :exc:`ValueError`
706    exception if there is an encoding error (the default of ``None`` has the same
707    effect), or pass ``'ignore'`` to ignore errors.  (Note that ignoring encoding
708    errors can lead to data loss.)  ``'replace'`` causes a replacement marker
709    (such as ``'?'``) to be inserted where there is malformed data.  When
710    writing, ``'xmlcharrefreplace'`` (replace with the appropriate XML character
711    reference) or ``'backslashreplace'`` (replace with backslashed escape
712    sequences) can be used.  Any other error handling name that has been
713    registered with :func:`codecs.register_error` is also valid.
715    *newline* can be ``None``, ``''``, ``'\n'``, ``'\r'``, or ``'\r\n'``.  It
716    controls the handling of line endings.  If it is ``None``, universal newlines
717    is enabled.  With this enabled, on input, the lines endings ``'\n'``,
718    ``'\r'``, or ``'\r\n'`` are translated to ``'\n'`` before being returned to
719    the caller.  Conversely, on output, ``'\n'`` is translated to the system
720    default line separator, :data:`os.linesep`.  If *newline* is any other of its
721    legal values, that newline becomes the newline when the file is read and it
722    is returned untranslated.  On output, ``'\n'`` is converted to the *newline*.
724    If *line_buffering* is ``True``, :meth:`flush` is implied when a call to
725    write contains a newline character.
727    :class:`TextIOWrapper` provides one attribute in addition to those of
728    :class:`TextIOBase` and its parents:
730    .. attribute:: line_buffering
732       Whether line buffering is enabled.
735 .. class:: StringIO(initial_value='', newline=None)
737    An in-memory stream for text I/O.
739    The initial value of the buffer (an empty string by default) can be set by
740    providing *initial_value*.  The *newline* argument works like that of
741    :class:`TextIOWrapper`.  The default is to do no newline translation.
743    :class:`StringIO` provides this method in addition to those from
744    :class:`TextIOBase` and its parents:
746    .. method:: getvalue()
748       Return a ``str`` containing the entire contents of the buffer at any
749       time before the :class:`StringIO` object's :meth:`close` method is
750       called.
752    Example usage::
754       import io
756       output = io.StringIO()
757       output.write('First line.\n')
758       print('Second line.', file=output)
760       # Retrieve file contents -- this will be
761       # 'First line.\nSecond line.\n'
762       contents = output.getvalue()
764       # Close object and discard memory buffer --
765       # .getvalue() will now raise an exception.
766       output.close()
768    .. note::
770       :class:`StringIO` uses a native text storage and doesn't suffer from the
771       performance issues of other text streams, such as those based on
772       :class:`TextIOWrapper`.
774 .. class:: IncrementalNewlineDecoder
776    A helper codec that decodes newlines for universal newlines mode.  It
777    inherits :class:`codecs.IncrementalDecoder`.