blob: 4a13d54135ded214ad98cdcadc77d719281d43f8 [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
Antoine Pitroub530e142010-08-30 12:41:00 +000014Overview
15--------
Georg Brandl014197c2008-04-09 18:40:51 +000016
Antoine Pitroub530e142010-08-30 12:41:00 +000017The :mod:`io` module provides Python 3's main facilities for dealing for
18various types of I/O. Three main types of I/O are defined: *text I/O*,
19*binary I/O*, *raw I/O*. It should be noted that these are generic categories,
20and various backing stores can be used for each of them. Concrete objects
21belonging to any of these categories will often be called *streams*; another
22common term is *file-like objects*.
Georg Brandl014197c2008-04-09 18:40:51 +000023
Antoine Pitroub530e142010-08-30 12:41:00 +000024Independently of its category, each concrete stream object will also have
25various capabilities: it can be read-only, write-only, or read-write; it
26can also allow arbitrary random access (seeking forwards or backwards to
27any location), or only sequential access (for example in the case of a
28socket or pipe).
Georg Brandl014197c2008-04-09 18:40:51 +000029
Antoine Pitroub530e142010-08-30 12:41:00 +000030All streams are careful about the type of data you give to them. For example
31giving a :class:`str` object to the ``write()`` method of a binary stream
32will raise a ``TypeError``. So will giving a :class:`bytes` object to the
33``write()`` method of a text stream.
Georg Brandl014197c2008-04-09 18:40:51 +000034
Antoine Pitroub530e142010-08-30 12:41:00 +000035Text I/O
36^^^^^^^^
Georg Brandl014197c2008-04-09 18:40:51 +000037
Antoine Pitroub530e142010-08-30 12:41:00 +000038Text I/O expects and produces :class:`str` objects. This means that,
39whenever the backing store is natively made of bytes (such as in the case
40of a file), encoding and decoding of data is made transparently, as well as,
41optionally, translation of platform-specific newline characters.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +000042
Antoine Pitroub530e142010-08-30 12:41:00 +000043A way to create a text stream is to :meth:`open()` a file in text mode,
44optionally specifying an encoding::
45
46 f = open("myfile.txt", "r", encoding="utf-8")
47
48In-memory text streams are also available as :class:`StringIO` objects::
49
50 f = io.StringIO("some initial text data")
51
52The detailed API of text streams is described by the :class:`TextIOBase`
53class.
54
55.. note::
56 Text I/O over a binary storage (such as a file) is significantly
57 slower than binary I/O over the same storage. This can become noticeable
58 if you handle huge amounts of text data (for example very large log files).
59
60Binary I/O
61^^^^^^^^^^
62
63Binary I/O (also called *buffered I/O*) expects and produces
64:class:`bytes` objects. No encoding, decoding or character translation
65is performed. This is the category of streams used for all kinds of non-text
66data, and also when manual control over the handling of text data is desired.
67
68A way to create a binary stream is to :meth:`open()` a file in binary mode::
69
70 f = open("myfile.jpg", "rb")
71
72In-memory binary streams are also available as :class:`BytesIO` objects::
73
74 f = io.BytesIO(b"some initial binary data: \x00\x01")
75
76The detailed API of binary streams is described by the :class:`BufferedIOBase`
77class.
78
79Other library modules may provide additional ways to create text or binary
80streams. See for example :meth:`socket.socket.makefile`.
81
82Raw I/O
83^^^^^^^
84
85Raw I/O (also called *unbuffered I/O*) is generally used as a low-level
86building-block for binary and text streams; it is rarely useful to directly
87manipulate a raw stream from user code. Nevertheless, you can for example
88create a raw stream by opening a file in binary mode with buffering disabled::
89
90 f = open("myfile.jpg", "rb", buffering=0)
91
92The detailed API of raw streams is described by the :class:`RawIOBase`
93class.
Benjamin Petersoncc12e1b2010-02-19 00:58:13 +000094
Georg Brandl014197c2008-04-09 18:40:51 +000095
Antoine Pitroub530e142010-08-30 12:41:00 +000096High-level Module Interface
97---------------------------
Georg Brandl014197c2008-04-09 18:40:51 +000098
99.. data:: DEFAULT_BUFFER_SIZE
100
101 An int containing the default buffer size used by the module's buffered I/O
Georg Brandl502d9a52009-07-26 15:02:41 +0000102 classes. :func:`.open` uses the file's blksize (as obtained by
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000103 :func:`os.stat`) if possible.
Georg Brandl014197c2008-04-09 18:40:51 +0000104
Benjamin Peterson95e392c2010-04-27 21:07:21 +0000105.. function:: open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True)
Georg Brandl014197c2008-04-09 18:40:51 +0000106
Benjamin Peterson52c3bf12009-03-23 02:44:58 +0000107 Open *file* and return a corresponding stream. If the file cannot be opened,
108 an :exc:`IOError` is raised.
Georg Brandl014197c2008-04-09 18:40:51 +0000109
Georg Brandl70f355d2010-07-19 06:52:35 +0000110 *file* is either a string or bytes object giving the pathname (absolute or
111 relative to the current working directory) of the file to be opened or
Benjamin Peterson52c3bf12009-03-23 02:44:58 +0000112 an integer file descriptor of the file to be wrapped. (If a file descriptor
113 is given, it is closed when the returned I/O object is closed, unless
114 *closefd* is set to ``False``.)
Georg Brandl014197c2008-04-09 18:40:51 +0000115
Benjamin Petersondd219122008-04-11 21:17:32 +0000116 *mode* is an optional string that specifies the mode in which the file is
117 opened. It defaults to ``'r'`` which means open for reading in text mode.
118 Other common values are ``'w'`` for writing (truncating the file if it
119 already exists), and ``'a'`` for appending (which on *some* Unix systems,
120 means that *all* writes append to the end of the file regardless of the
121 current seek position). In text mode, if *encoding* is not specified the
122 encoding used is platform dependent. (For reading and writing raw bytes use
123 binary mode and leave *encoding* unspecified.) The available modes are:
Georg Brandl014197c2008-04-09 18:40:51 +0000124
125 ========= ===============================================================
126 Character Meaning
127 --------- ---------------------------------------------------------------
128 ``'r'`` open for reading (default)
129 ``'w'`` open for writing, truncating the file first
130 ``'a'`` open for writing, appending to the end of the file if it exists
131 ``'b'`` binary mode
132 ``'t'`` text mode (default)
133 ``'+'`` open a disk file for updating (reading and writing)
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000134 ``'U'`` universal newline mode (for backwards compatibility; should
135 not be used in new code)
Georg Brandl014197c2008-04-09 18:40:51 +0000136 ========= ===============================================================
137
Antoine Pitroub530e142010-08-30 12:41:00 +0000138 The default mode is ``'r'`` (open for reading text, synonym of ``'rt'``).
139 For binary read-write access, the mode ``'w+b'`` opens and truncates the
140 file to 0 bytes, while ``'r+b'`` opens the file without truncation.
Georg Brandl014197c2008-04-09 18:40:51 +0000141
Antoine Pitroub530e142010-08-30 12:41:00 +0000142 As mentioned in the `overview`_, Python distinguishes between binary
143 and text I/O. Files opened in binary mode (including ``'b'`` in the
144 *mode* argument) return contents as :class:`bytes` objects without
145 any decoding. In text mode (the default, or when ``'t'``
146 is included in the *mode* argument), the contents of the file are
147 returned as strings, the bytes having been first decoded using a
148 platform-dependent encoding or using the specified *encoding* if given.
149
150 .. note::
151 Python doesn't depend on the underlying operating system's notion
152 of text files; all the the processing is done by Python itself, and
153 is therefore platform-independent.
Benjamin Petersondd219122008-04-11 21:17:32 +0000154
Antoine Pitroud5587bc2009-12-19 21:08:31 +0000155 *buffering* is an optional integer used to set the buffering policy.
156 Pass 0 to switch buffering off (only allowed in binary mode), 1 to select
157 line buffering (only usable in text mode), and an integer > 1 to indicate
158 the size of a fixed-size chunk buffer. When no *buffering* argument is
159 given, the default buffering policy works as follows:
160
161 * Binary files are buffered in fixed-size chunks; the size of the buffer
162 is chosen using a heuristic trying to determine the underlying device's
163 "block size" and falling back on :attr:`DEFAULT_BUFFER_SIZE`.
164 On many systems, the buffer will typically be 4096 or 8192 bytes long.
165
166 * "Interactive" text files (files for which :meth:`isatty` returns True)
167 use line buffering. Other text files use the policy described above
168 for binary files.
Georg Brandl014197c2008-04-09 18:40:51 +0000169
170 *encoding* is the name of the encoding used to decode or encode the file.
Benjamin Petersondd219122008-04-11 21:17:32 +0000171 This should only be used in text mode. The default encoding is platform
Benjamin Peterson52c3bf12009-03-23 02:44:58 +0000172 dependent (whatever :func:`locale.getpreferredencoding` returns), but any
173 encoding supported by Python can be used. See the :mod:`codecs` module for
174 the list of supported encodings.
Georg Brandl014197c2008-04-09 18:40:51 +0000175
Benjamin Petersonb85a5842008-04-13 21:39:58 +0000176 *errors* is an optional string that specifies how encoding and decoding
Benjamin Peterson52c3bf12009-03-23 02:44:58 +0000177 errors are to be handled--this cannot be used in binary mode. Pass
178 ``'strict'`` to raise a :exc:`ValueError` exception if there is an encoding
179 error (the default of ``None`` has the same effect), or pass ``'ignore'`` to
180 ignore errors. (Note that ignoring encoding errors can lead to data loss.)
181 ``'replace'`` causes a replacement marker (such as ``'?'``) to be inserted
182 where there is malformed data. When writing, ``'xmlcharrefreplace'``
183 (replace with the appropriate XML character reference) or
184 ``'backslashreplace'`` (replace with backslashed escape sequences) can be
185 used. Any other error handling name that has been registered with
186 :func:`codecs.register_error` is also valid.
Georg Brandl014197c2008-04-09 18:40:51 +0000187
188 *newline* controls how universal newlines works (it only applies to text
189 mode). It can be ``None``, ``''``, ``'\n'``, ``'\r'``, and ``'\r\n'``. It
190 works as follows:
191
192 * On input, if *newline* is ``None``, universal newlines mode is enabled.
193 Lines in the input can end in ``'\n'``, ``'\r'``, or ``'\r\n'``, and these
194 are translated into ``'\n'`` before being returned to the caller. If it is
195 ``''``, universal newline mode is enabled, but line endings are returned to
196 the caller untranslated. If it has any of the other legal values, input
197 lines are only terminated by the given string, and the line ending is
198 returned to the caller untranslated.
199
200 * On output, if *newline* is ``None``, any ``'\n'`` characters written are
201 translated to the system default line separator, :data:`os.linesep`. If
202 *newline* is ``''``, no translation takes place. If *newline* is any of
203 the other legal values, any ``'\n'`` characters written are translated to
204 the given string.
205
Benjamin Peterson8cad9c72009-03-23 02:38:01 +0000206 If *closefd* is ``False`` and a file descriptor rather than a filename was
207 given, the underlying file descriptor will be kept open when the file is
208 closed. If a filename is given *closefd* has no effect and must be ``True``
209 (the default).
Georg Brandl014197c2008-04-09 18:40:51 +0000210
Georg Brandl502d9a52009-07-26 15:02:41 +0000211 The type of file object returned by the :func:`.open` function depends on the
212 mode. When :func:`.open` is used to open a file in a text mode (``'w'``,
Benjamin Peterson8cad9c72009-03-23 02:38:01 +0000213 ``'r'``, ``'wt'``, ``'rt'``, etc.), it returns a subclass of
214 :class:`TextIOBase` (specifically :class:`TextIOWrapper`). When used to open
215 a file in a binary mode with buffering, the returned class is a subclass of
216 :class:`BufferedIOBase`. The exact class varies: in read binary mode, it
217 returns a :class:`BufferedReader`; in write binary and append binary modes,
218 it returns a :class:`BufferedWriter`, and in read/write mode, it returns a
219 :class:`BufferedRandom`. When buffering is disabled, the raw stream, a
220 subclass of :class:`RawIOBase`, :class:`FileIO`, is returned.
Georg Brandl014197c2008-04-09 18:40:51 +0000221
Georg Brandl014197c2008-04-09 18:40:51 +0000222
223.. exception:: BlockingIOError
224
225 Error raised when blocking would occur on a non-blocking stream. It inherits
226 :exc:`IOError`.
227
228 In addition to those of :exc:`IOError`, :exc:`BlockingIOError` has one
229 attribute:
230
231 .. attribute:: characters_written
232
233 An integer containing the number of characters written to the stream
234 before it blocked.
235
236
237.. exception:: UnsupportedOperation
238
239 An exception inheriting :exc:`IOError` and :exc:`ValueError` that is raised
240 when an unsupported operation is called on a stream.
241
242
Antoine Pitroub530e142010-08-30 12:41:00 +0000243In-memory streams
244^^^^^^^^^^^^^^^^^
245
246It is also possible to use a :class:`str` or :class:`bytes`-like object as a
247file for both reading and writing. For strings :class:`StringIO` can be
248used like a file opened in text mode, and :class:`BytesIO` can be used like
249a file opened in binary mode. Both provide full read-write capabilities
250with random access.
251
252
253.. seealso::
254 :mod:`sys`
255 contains the standard IO streams: :data:`sys.stdin`, :data:`sys.stdout`,
256 and :data:`sys.stderr`.
257
258
259Class hierarchy
260---------------
261
262The implementation of I/O streams is organized as a hierarchy of classes.
263First :term:`abstract base classes <abstract base class>` (ABCs), which are used to specify the
264various categories of streams, then concrete classes providing the standard
265stream implementations.
266
267 .. note::
268 The abstract base classes also provide default implementations of
269 some methods in order to help implementation of concrete stream
270 classes. For example, :class:`BufferedIOBase` provides
271 unoptimized implementations of ``readinto()`` and ``readline()``.
272
273At the top of the I/O hierarchy is the abstract base class :class:`IOBase`. It
274defines the basic interface to a stream. Note, however, that there is no
275separation between reading and writing to streams; implementations are allowed
276to raise an :exc:`UnsupportedOperation` if they do not support a given
277operation.
278
279Extending :class:`IOBase` is the :class:`RawIOBase` ABC which deals simply
280with the reading and writing of raw bytes to a stream. :class:`FileIO`
281subclasses :class:`RawIOBase` to provide an interface to files in the
282machine's file system.
283
284The :class:`BufferedIOBase` ABC deals with buffering on a raw byte stream
285(:class:`RawIOBase`). Its subclasses, :class:`BufferedWriter`,
286:class:`BufferedReader`, and :class:`BufferedRWPair` buffer streams that are
287readable, writable, and both readable and writable.
288:class:`BufferedRandom` provides a buffered interface to random access
289streams. :class:`BytesIO` is a simple stream of in-memory bytes.
290
291Another :class:`IOBase` subclass, the :class:`TextIOBase` ABC, deals with
292streams whose bytes represent text, and handles encoding and decoding
293from and to strings. :class:`TextIOWrapper`, which extends it, is a
294buffered text interface to a buffered raw stream
295(:class:`BufferedIOBase`). Finally, :class:`StringIO` is an in-memory
296stream for text.
297
298Argument names are not part of the specification, and only the arguments of
299:func:`.open` are intended to be used as keyword arguments.
300
301
Georg Brandl014197c2008-04-09 18:40:51 +0000302I/O Base Classes
Antoine Pitroub530e142010-08-30 12:41:00 +0000303^^^^^^^^^^^^^^^^
Georg Brandl014197c2008-04-09 18:40:51 +0000304
305.. class:: IOBase
306
307 The abstract base class for all I/O classes, acting on streams of bytes.
308 There is no public constructor.
309
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000310 This class provides empty abstract implementations for many methods
311 that derived classes can override selectively; the default
312 implementations represent a file that cannot be read, written or
313 seeked.
Georg Brandl014197c2008-04-09 18:40:51 +0000314
315 Even though :class:`IOBase` does not declare :meth:`read`, :meth:`readinto`,
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000316 or :meth:`write` because their signatures will vary, implementations and
317 clients should consider those methods part of the interface. Also,
318 implementations may raise a :exc:`IOError` when operations they do not
319 support are called.
Georg Brandl014197c2008-04-09 18:40:51 +0000320
321 The basic type used for binary data read from or written to a file is
322 :class:`bytes`. :class:`bytearray`\s are accepted too, and in some cases
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000323 (such as :class:`readinto`) required. Text I/O classes work with
324 :class:`str` data.
Georg Brandl014197c2008-04-09 18:40:51 +0000325
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000326 Note that calling any method (even inquiries) on a closed stream is
327 undefined. Implementations may raise :exc:`IOError` in this case.
Georg Brandl014197c2008-04-09 18:40:51 +0000328
329 IOBase (and its subclasses) support the iterator protocol, meaning that an
330 :class:`IOBase` object can be iterated over yielding the lines in a stream.
Antoine Pitrou497a7672009-09-17 17:18:01 +0000331 Lines are defined slightly differently depending on whether the stream is
332 a binary stream (yielding bytes), or a text stream (yielding character
333 strings). See :meth:`readline` below.
Georg Brandl014197c2008-04-09 18:40:51 +0000334
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000335 IOBase is also a context manager and therefore supports the
336 :keyword:`with` statement. In this example, *file* is closed after the
337 :keyword:`with` statement's suite is finished---even if an exception occurs::
Georg Brandl014197c2008-04-09 18:40:51 +0000338
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000339 with open('spam.txt', 'w') as file:
340 file.write('Spam and eggs!')
Georg Brandl014197c2008-04-09 18:40:51 +0000341
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000342 :class:`IOBase` provides these data attributes and methods:
Georg Brandl014197c2008-04-09 18:40:51 +0000343
344 .. method:: close()
345
Christian Heimesecc42a22008-11-05 19:30:32 +0000346 Flush and close this stream. This method has no effect if the file is
Georg Brandl48310cd2009-01-03 21:18:54 +0000347 already closed. Once the file is closed, any operation on the file
Georg Brandl8569e582010-05-19 20:57:08 +0000348 (e.g. reading or writing) will raise a :exc:`ValueError`.
Antoine Pitrouf9fc08f2010-04-28 19:59:32 +0000349
350 As a convenience, it is allowed to call this method more than once;
351 only the first call, however, will have an effect.
Georg Brandl014197c2008-04-09 18:40:51 +0000352
353 .. attribute:: closed
354
355 True if the stream is closed.
356
357 .. method:: fileno()
358
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000359 Return the underlying file descriptor (an integer) of the stream if it
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000360 exists. An :exc:`IOError` is raised if the IO object does not use a file
Georg Brandl014197c2008-04-09 18:40:51 +0000361 descriptor.
362
363 .. method:: flush()
364
Benjamin Petersonb85a5842008-04-13 21:39:58 +0000365 Flush the write buffers of the stream if applicable. This does nothing
366 for read-only and non-blocking streams.
Georg Brandl014197c2008-04-09 18:40:51 +0000367
368 .. method:: isatty()
369
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000370 Return ``True`` if the stream is interactive (i.e., connected to
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000371 a terminal/tty device).
Georg Brandl014197c2008-04-09 18:40:51 +0000372
373 .. method:: readable()
374
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000375 Return ``True`` if the stream can be read from. If False, :meth:`read`
376 will raise :exc:`IOError`.
Georg Brandl014197c2008-04-09 18:40:51 +0000377
Georg Brandl3dd33882009-06-01 17:35:27 +0000378 .. method:: readline(limit=-1)
Georg Brandl014197c2008-04-09 18:40:51 +0000379
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000380 Read and return one line from the stream. If *limit* is specified, at
381 most *limit* bytes will be read.
Georg Brandl014197c2008-04-09 18:40:51 +0000382
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000383 The line terminator is always ``b'\n'`` for binary files; for text files,
Georg Brandl502d9a52009-07-26 15:02:41 +0000384 the *newlines* argument to :func:`.open` can be used to select the line
Georg Brandl014197c2008-04-09 18:40:51 +0000385 terminator(s) recognized.
386
Georg Brandl3dd33882009-06-01 17:35:27 +0000387 .. method:: readlines(hint=-1)
Georg Brandl014197c2008-04-09 18:40:51 +0000388
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000389 Read and return a list of lines from the stream. *hint* can be specified
390 to control the number of lines read: no more lines will be read if the
391 total size (in bytes/characters) of all lines so far exceeds *hint*.
Georg Brandl014197c2008-04-09 18:40:51 +0000392
Georg Brandl3dd33882009-06-01 17:35:27 +0000393 .. method:: seek(offset, whence=SEEK_SET)
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000394
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000395 Change the stream position to the given byte *offset*. *offset* is
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000396 interpreted relative to the position indicated by *whence*. Values for
397 *whence* are:
398
Benjamin Peterson0e4caf42009-04-01 21:22:20 +0000399 * :data:`SEEK_SET` or ``0`` -- start of the stream (the default);
400 *offset* should be zero or positive
401 * :data:`SEEK_CUR` or ``1`` -- current stream position; *offset* may
402 be negative
403 * :data:`SEEK_END` or ``2`` -- end of the stream; *offset* is usually
404 negative
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000405
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000406 Return the new absolute position.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000407
Raymond Hettinger35a88362009-04-09 00:08:24 +0000408 .. versionadded:: 3.1
Georg Brandl67b21b72010-08-17 15:07:14 +0000409 The ``SEEK_*`` constants.
Benjamin Peterson0e4caf42009-04-01 21:22:20 +0000410
Georg Brandl014197c2008-04-09 18:40:51 +0000411 .. method:: seekable()
412
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000413 Return ``True`` if the stream supports random access. If ``False``,
414 :meth:`seek`, :meth:`tell` and :meth:`truncate` will raise :exc:`IOError`.
Georg Brandl014197c2008-04-09 18:40:51 +0000415
416 .. method:: tell()
417
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000418 Return the current stream position.
Georg Brandl014197c2008-04-09 18:40:51 +0000419
Georg Brandl3dd33882009-06-01 17:35:27 +0000420 .. method:: truncate(size=None)
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000421
Antoine Pitrou2016dc92010-05-29 12:08:25 +0000422 Resize the stream to the given *size* in bytes (or the current position
423 if *size* is not specified). The current stream position isn't changed.
424 This resizing can extend or reduce the current file size. In case of
425 extension, the contents of the new file area depend on the platform
426 (on most systems, additional bytes are zero-filled, on Windows they're
427 undetermined). The new file size is returned.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000428
Georg Brandl014197c2008-04-09 18:40:51 +0000429 .. method:: writable()
430
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000431 Return ``True`` if the stream supports writing. If ``False``,
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000432 :meth:`write` and :meth:`truncate` will raise :exc:`IOError`.
Georg Brandl014197c2008-04-09 18:40:51 +0000433
434 .. method:: writelines(lines)
435
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000436 Write a list of lines to the stream. Line separators are not added, so it
437 is usual for each of the lines provided to have a line separator at the
438 end.
Georg Brandl014197c2008-04-09 18:40:51 +0000439
440
441.. class:: RawIOBase
442
443 Base class for raw binary I/O. It inherits :class:`IOBase`. There is no
444 public constructor.
445
Antoine Pitrou497a7672009-09-17 17:18:01 +0000446 Raw binary I/O typically provides low-level access to an underlying OS
447 device or API, and does not try to encapsulate it in high-level primitives
448 (this is left to Buffered I/O and Text I/O, described later in this page).
449
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000450 In addition to the attributes and methods from :class:`IOBase`,
451 RawIOBase provides the following methods:
Georg Brandl014197c2008-04-09 18:40:51 +0000452
Georg Brandl3dd33882009-06-01 17:35:27 +0000453 .. method:: read(n=-1)
Georg Brandl014197c2008-04-09 18:40:51 +0000454
Antoine Pitrou78ddbe62009-10-01 16:24:45 +0000455 Read up to *n* bytes from the object and return them. As a convenience,
456 if *n* is unspecified or -1, :meth:`readall` is called. Otherwise,
457 only one system call is ever made. Fewer than *n* bytes may be
458 returned if the operating system call returns fewer than *n* bytes.
459
460 If 0 bytes are returned, and *n* was not 0, this indicates end of file.
461 If the object is in non-blocking mode and no bytes are available,
462 ``None`` is returned.
Georg Brandl014197c2008-04-09 18:40:51 +0000463
Benjamin Petersonb47aace2008-04-09 21:38:38 +0000464 .. method:: readall()
Georg Brandl014197c2008-04-09 18:40:51 +0000465
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000466 Read and return all the bytes from the stream until EOF, using multiple
467 calls to the stream if necessary.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000468
469 .. method:: readinto(b)
470
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000471 Read up to len(b) bytes into bytearray *b* and return the number of bytes
472 read.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000473
474 .. method:: write(b)
475
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000476 Write the given bytes or bytearray object, *b*, to the underlying raw
Antoine Pitrou497a7672009-09-17 17:18:01 +0000477 stream and return the number of bytes written. This can be less than
478 ``len(b)``, depending on specifics of the underlying raw stream, and
479 especially if it is in non-blocking mode. ``None`` is returned if the
480 raw stream is set not to block and no single byte could be readily
481 written to it.
Georg Brandl014197c2008-04-09 18:40:51 +0000482
483
Georg Brandl014197c2008-04-09 18:40:51 +0000484.. class:: BufferedIOBase
485
Antoine Pitrou497a7672009-09-17 17:18:01 +0000486 Base class for binary streams that support some kind of buffering.
487 It inherits :class:`IOBase`. There is no public constructor.
Georg Brandl014197c2008-04-09 18:40:51 +0000488
Antoine Pitrou497a7672009-09-17 17:18:01 +0000489 The main difference with :class:`RawIOBase` is that methods :meth:`read`,
490 :meth:`readinto` and :meth:`write` will try (respectively) to read as much
491 input as requested or to consume all given output, at the expense of
492 making perhaps more than one system call.
493
494 In addition, those methods can raise :exc:`BlockingIOError` if the
495 underlying raw stream is in non-blocking mode and cannot take or give
496 enough data; unlike their :class:`RawIOBase` counterparts, they will
497 never return ``None``.
498
499 Besides, the :meth:`read` method does not have a default
Georg Brandl014197c2008-04-09 18:40:51 +0000500 implementation that defers to :meth:`readinto`.
501
Antoine Pitrou497a7672009-09-17 17:18:01 +0000502 A typical :class:`BufferedIOBase` implementation should not inherit from a
503 :class:`RawIOBase` implementation, but wrap one, like
504 :class:`BufferedWriter` and :class:`BufferedReader` do.
Georg Brandl014197c2008-04-09 18:40:51 +0000505
Benjamin Petersonc609b6b2009-06-28 17:32:20 +0000506 :class:`BufferedIOBase` provides or overrides these members in addition to
Georg Brandl014197c2008-04-09 18:40:51 +0000507 those from :class:`IOBase`:
508
Benjamin Petersonc609b6b2009-06-28 17:32:20 +0000509 .. attribute:: raw
510
511 The underlying raw stream (a :class:`RawIOBase` instance) that
512 :class:`BufferedIOBase` deals with. This is not part of the
513 :class:`BufferedIOBase` API and may not exist on some implementations.
514
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000515 .. method:: detach()
516
517 Separate the underlying raw stream from the buffer and return it.
518
519 After the raw stream has been detached, the buffer is in an unusable
520 state.
521
522 Some buffers, like :class:`BytesIO`, do not have the concept of a single
523 raw stream to return from this method. They raise
524 :exc:`UnsupportedOperation`.
525
Benjamin Petersonedc36472009-05-01 20:48:14 +0000526 .. versionadded:: 3.1
527
Georg Brandl3dd33882009-06-01 17:35:27 +0000528 .. method:: read(n=-1)
Georg Brandl014197c2008-04-09 18:40:51 +0000529
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000530 Read and return up to *n* bytes. If the argument is omitted, ``None``, or
Georg Brandl014197c2008-04-09 18:40:51 +0000531 negative, data is read and returned until EOF is reached. An empty bytes
532 object is returned if the stream is already at EOF.
533
534 If the argument is positive, and the underlying raw stream is not
535 interactive, multiple raw reads may be issued to satisfy the byte count
536 (unless EOF is reached first). But for interactive raw streams, at most
537 one raw read will be issued, and a short result does not imply that EOF is
538 imminent.
539
Antoine Pitrou497a7672009-09-17 17:18:01 +0000540 A :exc:`BlockingIOError` is raised if the underlying raw stream is in
541 non blocking-mode, and has no data available at the moment.
Georg Brandl014197c2008-04-09 18:40:51 +0000542
Georg Brandl3dd33882009-06-01 17:35:27 +0000543 .. method:: read1(n=-1)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000544
545 Read and return up to *n* bytes, with at most one call to the underlying
Antoine Pitrou497a7672009-09-17 17:18:01 +0000546 raw stream's :meth:`~RawIOBase.read` method. This can be useful if you
547 are implementing your own buffering on top of a :class:`BufferedIOBase`
548 object.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000549
Georg Brandl014197c2008-04-09 18:40:51 +0000550 .. method:: readinto(b)
551
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000552 Read up to len(b) bytes into bytearray *b* and return the number of bytes
Georg Brandl014197c2008-04-09 18:40:51 +0000553 read.
554
555 Like :meth:`read`, multiple reads may be issued to the underlying raw
Antoine Pitrou497a7672009-09-17 17:18:01 +0000556 stream, unless the latter is 'interactive'.
Georg Brandl014197c2008-04-09 18:40:51 +0000557
Antoine Pitrou497a7672009-09-17 17:18:01 +0000558 A :exc:`BlockingIOError` is raised if the underlying raw stream is in
559 non blocking-mode, and has no data available at the moment.
Georg Brandl014197c2008-04-09 18:40:51 +0000560
Georg Brandl014197c2008-04-09 18:40:51 +0000561 .. method:: write(b)
562
Antoine Pitrou497a7672009-09-17 17:18:01 +0000563 Write the given bytes or bytearray object, *b* and return the number
564 of bytes written (never less than ``len(b)``, since if the write fails
565 an :exc:`IOError` will be raised). Depending on the actual
566 implementation, these bytes may be readily written to the underlying
567 stream, or held in a buffer for performance and latency reasons.
Georg Brandl014197c2008-04-09 18:40:51 +0000568
Antoine Pitrou497a7672009-09-17 17:18:01 +0000569 When in non-blocking mode, a :exc:`BlockingIOError` is raised if the
570 data needed to be written to the raw stream but it couldn't accept
571 all the data without blocking.
Georg Brandl014197c2008-04-09 18:40:51 +0000572
573
Benjamin Petersonaa069002009-01-23 03:26:36 +0000574Raw File I/O
Antoine Pitroub530e142010-08-30 12:41:00 +0000575^^^^^^^^^^^^
Benjamin Petersonaa069002009-01-23 03:26:36 +0000576
Georg Brandl3dd33882009-06-01 17:35:27 +0000577.. class:: FileIO(name, mode='r', closefd=True)
Benjamin Petersonaa069002009-01-23 03:26:36 +0000578
Antoine Pitrou497a7672009-09-17 17:18:01 +0000579 :class:`FileIO` represents an OS-level file containing bytes data.
580 It implements the :class:`RawIOBase` interface (and therefore the
581 :class:`IOBase` interface, too).
582
583 The *name* can be one of two things:
584
585 * a character string or bytes object representing the path to the file
586 which will be opened;
587 * an integer representing the number of an existing OS-level file descriptor
588 to which the resulting :class:`FileIO` object will give access.
Benjamin Petersonaa069002009-01-23 03:26:36 +0000589
590 The *mode* can be ``'r'``, ``'w'`` or ``'a'`` for reading (default), writing,
591 or appending. The file will be created if it doesn't exist when opened for
592 writing or appending; it will be truncated when opened for writing. Add a
593 ``'+'`` to the mode to allow simultaneous reading and writing.
594
Antoine Pitrou497a7672009-09-17 17:18:01 +0000595 The :meth:`read` (when called with a positive argument), :meth:`readinto`
596 and :meth:`write` methods on this class will only make one system call.
597
Benjamin Petersonaa069002009-01-23 03:26:36 +0000598 In addition to the attributes and methods from :class:`IOBase` and
599 :class:`RawIOBase`, :class:`FileIO` provides the following data
600 attributes and methods:
601
602 .. attribute:: mode
603
604 The mode as given in the constructor.
605
606 .. attribute:: name
607
608 The file name. This is the file descriptor of the file when no name is
609 given in the constructor.
610
Benjamin Petersonaa069002009-01-23 03:26:36 +0000611
612Buffered Streams
Antoine Pitroub530e142010-08-30 12:41:00 +0000613^^^^^^^^^^^^^^^^
Benjamin Petersonaa069002009-01-23 03:26:36 +0000614
Antoine Pitrou497a7672009-09-17 17:18:01 +0000615In many situations, buffered I/O streams will provide higher performance
616(bandwidth and latency) than raw I/O streams. Their API is also more usable.
617
Georg Brandl014197c2008-04-09 18:40:51 +0000618.. class:: BytesIO([initial_bytes])
619
620 A stream implementation using an in-memory bytes buffer. It inherits
621 :class:`BufferedIOBase`.
622
Antoine Pitroub530e142010-08-30 12:41:00 +0000623 The argument *initial_bytes* contains optional initial :class:`bytes` data.
Georg Brandl014197c2008-04-09 18:40:51 +0000624
625 :class:`BytesIO` provides or overrides these methods in addition to those
626 from :class:`BufferedIOBase` and :class:`IOBase`:
627
628 .. method:: getvalue()
629
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000630 Return ``bytes`` containing the entire contents of the buffer.
Georg Brandl014197c2008-04-09 18:40:51 +0000631
632 .. method:: read1()
633
Benjamin Peterson9efcc4b2008-04-14 21:30:21 +0000634 In :class:`BytesIO`, this is the same as :meth:`read`.
Georg Brandl014197c2008-04-09 18:40:51 +0000635
Georg Brandl014197c2008-04-09 18:40:51 +0000636
Georg Brandl3dd33882009-06-01 17:35:27 +0000637.. class:: BufferedReader(raw, buffer_size=DEFAULT_BUFFER_SIZE)
Georg Brandl014197c2008-04-09 18:40:51 +0000638
Antoine Pitrou497a7672009-09-17 17:18:01 +0000639 A buffer providing higher-level access to a readable, sequential
640 :class:`RawIOBase` object. It inherits :class:`BufferedIOBase`.
641 When reading data from this object, a larger amount of data may be
642 requested from the underlying raw stream, and kept in an internal buffer.
643 The buffered data can then be returned directly on subsequent reads.
Georg Brandl014197c2008-04-09 18:40:51 +0000644
645 The constructor creates a :class:`BufferedReader` for the given readable
646 *raw* stream and *buffer_size*. If *buffer_size* is omitted,
647 :data:`DEFAULT_BUFFER_SIZE` is used.
648
649 :class:`BufferedReader` provides or overrides these methods in addition to
650 those from :class:`BufferedIOBase` and :class:`IOBase`:
651
652 .. method:: peek([n])
653
Benjamin Petersonc43a26d2009-06-16 23:09:24 +0000654 Return bytes from the stream without advancing the position. At most one
Benjamin Peterson2a8b54d2009-06-14 14:37:23 +0000655 single read on the raw stream is done to satisfy the call. The number of
656 bytes returned may be less or more than requested.
Georg Brandl014197c2008-04-09 18:40:51 +0000657
658 .. method:: read([n])
659
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000660 Read and return *n* bytes, or if *n* is not given or negative, until EOF
Georg Brandl014197c2008-04-09 18:40:51 +0000661 or if the read call would block in non-blocking mode.
662
663 .. method:: read1(n)
664
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000665 Read and return up to *n* bytes with only one call on the raw stream. If
Georg Brandl014197c2008-04-09 18:40:51 +0000666 at least one byte is buffered, only buffered bytes are returned.
667 Otherwise, one raw stream read call is made.
668
669
Georg Brandl3dd33882009-06-01 17:35:27 +0000670.. class:: BufferedWriter(raw, buffer_size=DEFAULT_BUFFER_SIZE)
Georg Brandl014197c2008-04-09 18:40:51 +0000671
Antoine Pitrou497a7672009-09-17 17:18:01 +0000672 A buffer providing higher-level access to a writeable, sequential
673 :class:`RawIOBase` object. It inherits :class:`BufferedIOBase`.
674 When writing to this object, data is normally held into an internal
675 buffer. The buffer will be written out to the underlying :class:`RawIOBase`
676 object under various conditions, including:
677
678 * when the buffer gets too small for all pending data;
679 * when :meth:`flush()` is called;
680 * when a :meth:`seek()` is requested (for :class:`BufferedRandom` objects);
681 * when the :class:`BufferedWriter` object is closed or destroyed.
Georg Brandl014197c2008-04-09 18:40:51 +0000682
683 The constructor creates a :class:`BufferedWriter` for the given writeable
684 *raw* stream. If the *buffer_size* is not given, it defaults to
Benjamin Peterson394ee002009-03-05 22:33:59 +0000685 :data:`DEFAULT_BUFFER_SIZE`.
686
Georg Brandl3dd33882009-06-01 17:35:27 +0000687 A third argument, *max_buffer_size*, is supported, but unused and deprecated.
Georg Brandl014197c2008-04-09 18:40:51 +0000688
689 :class:`BufferedWriter` provides or overrides these methods in addition to
690 those from :class:`BufferedIOBase` and :class:`IOBase`:
691
692 .. method:: flush()
693
694 Force bytes held in the buffer into the raw stream. A
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000695 :exc:`BlockingIOError` should be raised if the raw stream blocks.
Georg Brandl014197c2008-04-09 18:40:51 +0000696
697 .. method:: write(b)
698
Antoine Pitrou497a7672009-09-17 17:18:01 +0000699 Write the bytes or bytearray object, *b* and return the number of bytes
700 written. When in non-blocking mode, a :exc:`BlockingIOError` is raised
701 if the buffer needs to be written out but the raw stream blocks.
Georg Brandl014197c2008-04-09 18:40:51 +0000702
703
Antoine Pitrou497a7672009-09-17 17:18:01 +0000704.. class:: BufferedRWPair(reader, writer, buffer_size=DEFAULT_BUFFER_SIZE)
Georg Brandl014197c2008-04-09 18:40:51 +0000705
Antoine Pitrou497a7672009-09-17 17:18:01 +0000706 A buffered I/O object giving a combined, higher-level access to two
707 sequential :class:`RawIOBase` objects: one readable, the other writeable.
708 It is useful for pairs of unidirectional communication channels
709 (pipes, for instance). It inherits :class:`BufferedIOBase`.
Georg Brandl014197c2008-04-09 18:40:51 +0000710
711 *reader* and *writer* are :class:`RawIOBase` objects that are readable and
712 writeable respectively. If the *buffer_size* is omitted it defaults to
Benjamin Peterson394ee002009-03-05 22:33:59 +0000713 :data:`DEFAULT_BUFFER_SIZE`.
714
Georg Brandl3dd33882009-06-01 17:35:27 +0000715 A fourth argument, *max_buffer_size*, is supported, but unused and
716 deprecated.
Georg Brandl014197c2008-04-09 18:40:51 +0000717
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000718 :class:`BufferedRWPair` implements all of :class:`BufferedIOBase`\'s methods
719 except for :meth:`~BufferedIOBase.detach`, which raises
720 :exc:`UnsupportedOperation`.
Georg Brandl014197c2008-04-09 18:40:51 +0000721
722
Georg Brandl3dd33882009-06-01 17:35:27 +0000723.. class:: BufferedRandom(raw, buffer_size=DEFAULT_BUFFER_SIZE)
Georg Brandl014197c2008-04-09 18:40:51 +0000724
725 A buffered interface to random access streams. It inherits
Antoine Pitrou497a7672009-09-17 17:18:01 +0000726 :class:`BufferedReader` and :class:`BufferedWriter`, and further supports
727 :meth:`seek` and :meth:`tell` functionality.
Georg Brandl014197c2008-04-09 18:40:51 +0000728
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000729 The constructor creates a reader and writer for a seekable raw stream, given
Georg Brandl014197c2008-04-09 18:40:51 +0000730 in the first argument. If the *buffer_size* is omitted it defaults to
Benjamin Peterson394ee002009-03-05 22:33:59 +0000731 :data:`DEFAULT_BUFFER_SIZE`.
732
Georg Brandl3dd33882009-06-01 17:35:27 +0000733 A third argument, *max_buffer_size*, is supported, but unused and deprecated.
Georg Brandl014197c2008-04-09 18:40:51 +0000734
735 :class:`BufferedRandom` is capable of anything :class:`BufferedReader` or
736 :class:`BufferedWriter` can do.
737
738
739Text I/O
Antoine Pitroub530e142010-08-30 12:41:00 +0000740^^^^^^^^
Georg Brandl014197c2008-04-09 18:40:51 +0000741
742.. class:: TextIOBase
743
744 Base class for text streams. This class provides a character and line based
745 interface to stream I/O. There is no :meth:`readinto` method because
746 Python's character strings are immutable. It inherits :class:`IOBase`.
747 There is no public constructor.
748
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000749 :class:`TextIOBase` provides or overrides these data attributes and
750 methods in addition to those from :class:`IOBase`:
Georg Brandl014197c2008-04-09 18:40:51 +0000751
752 .. attribute:: encoding
753
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000754 The name of the encoding used to decode the stream's bytes into
Georg Brandl014197c2008-04-09 18:40:51 +0000755 strings, and to encode strings into bytes.
756
Benjamin Peterson0926ad12009-06-06 18:02:12 +0000757 .. attribute:: errors
758
759 The error setting of the decoder or encoder.
760
Georg Brandl014197c2008-04-09 18:40:51 +0000761 .. attribute:: newlines
762
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000763 A string, a tuple of strings, or ``None``, indicating the newlines
Antoine Pitrou497a7672009-09-17 17:18:01 +0000764 translated so far. Depending on the implementation and the initial
765 constructor flags, this may not be available.
Georg Brandl014197c2008-04-09 18:40:51 +0000766
Benjamin Petersonc609b6b2009-06-28 17:32:20 +0000767 .. attribute:: buffer
768
769 The underlying binary buffer (a :class:`BufferedIOBase` instance) that
770 :class:`TextIOBase` deals with. This is not part of the
771 :class:`TextIOBase` API and may not exist on some implementations.
772
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000773 .. method:: detach()
774
Antoine Pitrou497a7672009-09-17 17:18:01 +0000775 Separate the underlying binary buffer from the :class:`TextIOBase` and
776 return it.
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000777
778 After the underlying buffer has been detached, the :class:`TextIOBase` is
779 in an unusable state.
780
781 Some :class:`TextIOBase` implementations, like :class:`StringIO`, may not
782 have the concept of an underlying buffer and calling this method will
783 raise :exc:`UnsupportedOperation`.
784
Benjamin Petersonedc36472009-05-01 20:48:14 +0000785 .. versionadded:: 3.1
786
Georg Brandl014197c2008-04-09 18:40:51 +0000787 .. method:: read(n)
788
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000789 Read and return at most *n* characters from the stream as a single
Antoine Pitrou497a7672009-09-17 17:18:01 +0000790 :class:`str`. If *n* is negative or ``None``, reads until EOF.
Georg Brandl014197c2008-04-09 18:40:51 +0000791
792 .. method:: readline()
793
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000794 Read until newline or EOF and return a single ``str``. If the stream is
795 already at EOF, an empty string is returned.
Georg Brandl014197c2008-04-09 18:40:51 +0000796
Georg Brandl014197c2008-04-09 18:40:51 +0000797 .. method:: write(s)
798
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000799 Write the string *s* to the stream and return the number of characters
800 written.
Georg Brandl014197c2008-04-09 18:40:51 +0000801
802
Georg Brandl3dd33882009-06-01 17:35:27 +0000803.. class:: TextIOWrapper(buffer, encoding=None, errors=None, newline=None, line_buffering=False)
Georg Brandl014197c2008-04-09 18:40:51 +0000804
Antoine Pitrou497a7672009-09-17 17:18:01 +0000805 A buffered text stream over a :class:`BufferedIOBase` binary stream.
Georg Brandl014197c2008-04-09 18:40:51 +0000806 It inherits :class:`TextIOBase`.
807
808 *encoding* gives the name of the encoding that the stream will be decoded or
809 encoded with. It defaults to :func:`locale.getpreferredencoding`.
810
Benjamin Petersonb85a5842008-04-13 21:39:58 +0000811 *errors* is an optional string that specifies how encoding and decoding
812 errors are to be handled. Pass ``'strict'`` to raise a :exc:`ValueError`
813 exception if there is an encoding error (the default of ``None`` has the same
814 effect), or pass ``'ignore'`` to ignore errors. (Note that ignoring encoding
815 errors can lead to data loss.) ``'replace'`` causes a replacement marker
Christian Heimesa342c012008-04-20 21:01:16 +0000816 (such as ``'?'``) to be inserted where there is malformed data. When
817 writing, ``'xmlcharrefreplace'`` (replace with the appropriate XML character
818 reference) or ``'backslashreplace'`` (replace with backslashed escape
819 sequences) can be used. Any other error handling name that has been
820 registered with :func:`codecs.register_error` is also valid.
Georg Brandl014197c2008-04-09 18:40:51 +0000821
822 *newline* can be ``None``, ``''``, ``'\n'``, ``'\r'``, or ``'\r\n'``. It
823 controls the handling of line endings. If it is ``None``, universal newlines
824 is enabled. With this enabled, on input, the lines endings ``'\n'``,
825 ``'\r'``, or ``'\r\n'`` are translated to ``'\n'`` before being returned to
826 the caller. Conversely, on output, ``'\n'`` is translated to the system
Mark Dickinson934896d2009-02-21 20:59:32 +0000827 default line separator, :data:`os.linesep`. If *newline* is any other of its
Georg Brandl014197c2008-04-09 18:40:51 +0000828 legal values, that newline becomes the newline when the file is read and it
829 is returned untranslated. On output, ``'\n'`` is converted to the *newline*.
830
831 If *line_buffering* is ``True``, :meth:`flush` is implied when a call to
832 write contains a newline character.
833
Benjamin Peterson0926ad12009-06-06 18:02:12 +0000834 :class:`TextIOWrapper` provides one attribute in addition to those of
Georg Brandl014197c2008-04-09 18:40:51 +0000835 :class:`TextIOBase` and its parents:
836
Georg Brandl014197c2008-04-09 18:40:51 +0000837 .. attribute:: line_buffering
838
839 Whether line buffering is enabled.
Georg Brandl48310cd2009-01-03 21:18:54 +0000840
Georg Brandl014197c2008-04-09 18:40:51 +0000841
Georg Brandl3dd33882009-06-01 17:35:27 +0000842.. class:: StringIO(initial_value='', newline=None)
Georg Brandl014197c2008-04-09 18:40:51 +0000843
Antoine Pitroub530e142010-08-30 12:41:00 +0000844 An in-memory stream for text I/O.
Georg Brandl014197c2008-04-09 18:40:51 +0000845
Benjamin Petersonaa1c8d82009-03-09 02:02:23 +0000846 The initial value of the buffer (an empty string by default) can be set by
847 providing *initial_value*. The *newline* argument works like that of
848 :class:`TextIOWrapper`. The default is to do no newline translation.
Georg Brandl014197c2008-04-09 18:40:51 +0000849
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000850 :class:`StringIO` provides this method in addition to those from
Antoine Pitroub530e142010-08-30 12:41:00 +0000851 :class:`TextIOBase` and its parents:
Georg Brandl014197c2008-04-09 18:40:51 +0000852
853 .. method:: getvalue()
854
Georg Brandl2932d932008-05-30 06:27:09 +0000855 Return a ``str`` containing the entire contents of the buffer at any
856 time before the :class:`StringIO` object's :meth:`close` method is
857 called.
Georg Brandl014197c2008-04-09 18:40:51 +0000858
Georg Brandl2932d932008-05-30 06:27:09 +0000859 Example usage::
860
861 import io
862
863 output = io.StringIO()
864 output.write('First line.\n')
865 print('Second line.', file=output)
866
867 # Retrieve file contents -- this will be
868 # 'First line.\nSecond line.\n'
869 contents = output.getvalue()
870
Georg Brandl48310cd2009-01-03 21:18:54 +0000871 # Close object and discard memory buffer --
Georg Brandl2932d932008-05-30 06:27:09 +0000872 # .getvalue() will now raise an exception.
873 output.close()
Georg Brandl014197c2008-04-09 18:40:51 +0000874
Antoine Pitroub530e142010-08-30 12:41:00 +0000875 .. note::
876 :class:`StringIO` uses a native text storage and doesn't suffer from
877 the performance issues of other text streams, such as those based on
878 :class:`TextIOWrapper`.
879
Georg Brandl014197c2008-04-09 18:40:51 +0000880.. class:: IncrementalNewlineDecoder
881
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000882 A helper codec that decodes newlines for universal newlines mode. It
883 inherits :class:`codecs.IncrementalDecoder`.
Georg Brandl014197c2008-04-09 18:40:51 +0000884