blob: 3e98ca9a02fd7a1ac07e74b2499ef24b042e8929 [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
14The :mod:`io` module provides the Python interfaces to stream handling. The
Georg Brandlc5605df2009-08-13 08:26:44 +000015built-in :func:`open` function is defined in this module.
Georg Brandl014197c2008-04-09 18:40:51 +000016
17At the top of the I/O hierarchy is the abstract base class :class:`IOBase`. It
18defines the basic interface to a stream. Note, however, that there is no
Mark Dickinson934896d2009-02-21 20:59:32 +000019separation between reading and writing to streams; implementations are allowed
Georg Brandl014197c2008-04-09 18:40:51 +000020to throw an :exc:`IOError` if they do not support a given operation.
21
22Extending :class:`IOBase` is :class:`RawIOBase` which deals simply with the
23reading and writing of raw bytes to a stream. :class:`FileIO` subclasses
Mark Summerfielde6d5f302008-04-21 10:29:45 +000024:class:`RawIOBase` to provide an interface to files in the machine's
25file system.
Georg Brandl014197c2008-04-09 18:40:51 +000026
27:class:`BufferedIOBase` deals with buffering on a raw byte stream
28(:class:`RawIOBase`). Its subclasses, :class:`BufferedWriter`,
29:class:`BufferedReader`, and :class:`BufferedRWPair` buffer streams that are
Mark Summerfielde6d5f302008-04-21 10:29:45 +000030readable, writable, and both readable and writable.
31:class:`BufferedRandom` provides a buffered interface to random access
32streams. :class:`BytesIO` is a simple stream of in-memory bytes.
Georg Brandl014197c2008-04-09 18:40:51 +000033
Mark Summerfielde6d5f302008-04-21 10:29:45 +000034Another :class:`IOBase` subclass, :class:`TextIOBase`, deals with
35streams whose bytes represent text, and handles encoding and decoding
36from and to strings. :class:`TextIOWrapper`, which extends it, is a
37buffered text interface to a buffered raw stream
38(:class:`BufferedIOBase`). Finally, :class:`StringIO` is an in-memory
39stream for text.
Georg Brandl014197c2008-04-09 18:40:51 +000040
Benjamin Peterson2c5f8282008-04-13 00:27:46 +000041Argument names are not part of the specification, and only the arguments of
Georg Brandlc5605df2009-08-13 08:26:44 +000042:func:`.open` are intended to be used as keyword arguments.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +000043
Georg Brandl014197c2008-04-09 18:40:51 +000044
45Module Interface
46----------------
47
48.. data:: DEFAULT_BUFFER_SIZE
49
50 An int containing the default buffer size used by the module's buffered I/O
Georg Brandlc5605df2009-08-13 08:26:44 +000051 classes. :func:`.open` uses the file's blksize (as obtained by
Benjamin Peterson2c5f8282008-04-13 00:27:46 +000052 :func:`os.stat`) if possible.
Georg Brandl014197c2008-04-09 18:40:51 +000053
Georg Brandl3dd33882009-06-01 17:35:27 +000054.. function:: open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True)
Georg Brandl014197c2008-04-09 18:40:51 +000055
Benjamin Peterson52c3bf12009-03-23 02:44:58 +000056 Open *file* and return a corresponding stream. If the file cannot be opened,
57 an :exc:`IOError` is raised.
Georg Brandl014197c2008-04-09 18:40:51 +000058
Benjamin Peterson52c3bf12009-03-23 02:44:58 +000059 *file* is either a string or bytes object giving the name (and the path if
60 the file isn't in the current working directory) of the file to be opened or
61 an integer file descriptor of the file to be wrapped. (If a file descriptor
62 is given, it is closed when the returned I/O object is closed, unless
63 *closefd* is set to ``False``.)
Georg Brandl014197c2008-04-09 18:40:51 +000064
Benjamin Petersondd219122008-04-11 21:17:32 +000065 *mode* is an optional string that specifies the mode in which the file is
66 opened. It defaults to ``'r'`` which means open for reading in text mode.
67 Other common values are ``'w'`` for writing (truncating the file if it
68 already exists), and ``'a'`` for appending (which on *some* Unix systems,
69 means that *all* writes append to the end of the file regardless of the
70 current seek position). In text mode, if *encoding* is not specified the
71 encoding used is platform dependent. (For reading and writing raw bytes use
72 binary mode and leave *encoding* unspecified.) The available modes are:
Georg Brandl014197c2008-04-09 18:40:51 +000073
74 ========= ===============================================================
75 Character Meaning
76 --------- ---------------------------------------------------------------
77 ``'r'`` open for reading (default)
78 ``'w'`` open for writing, truncating the file first
79 ``'a'`` open for writing, appending to the end of the file if it exists
80 ``'b'`` binary mode
81 ``'t'`` text mode (default)
82 ``'+'`` open a disk file for updating (reading and writing)
Mark Summerfielde6d5f302008-04-21 10:29:45 +000083 ``'U'`` universal newline mode (for backwards compatibility; should
84 not be used in new code)
Georg Brandl014197c2008-04-09 18:40:51 +000085 ========= ===============================================================
86
87 The default mode is ``'rt'`` (open for reading text). For binary random
88 access, the mode ``'w+b'`` opens and truncates the file to 0 bytes, while
89 ``'r+b'`` opens the file without truncation.
90
Benjamin Peterson2c5f8282008-04-13 00:27:46 +000091 Python distinguishes between files opened in binary and text modes, even when
92 the underlying operating system doesn't. Files opened in binary mode
Mark Summerfielde6d5f302008-04-21 10:29:45 +000093 (including ``'b'`` in the *mode* argument) return contents as ``bytes``
Benjamin Peterson2c5f8282008-04-13 00:27:46 +000094 objects without any decoding. In text mode (the default, or when ``'t'`` is
Mark Summerfielde6d5f302008-04-21 10:29:45 +000095 included in the *mode* argument), the contents of the file are returned as
Benjamin Peterson2c5f8282008-04-13 00:27:46 +000096 strings, the bytes having been first decoded using a platform-dependent
97 encoding or using the specified *encoding* if given.
Benjamin Petersondd219122008-04-11 21:17:32 +000098
Antoine Pitrou45a43722009-12-19 21:09:58 +000099 *buffering* is an optional integer used to set the buffering policy.
100 Pass 0 to switch buffering off (only allowed in binary mode), 1 to select
101 line buffering (only usable in text mode), and an integer > 1 to indicate
102 the size of a fixed-size chunk buffer. When no *buffering* argument is
103 given, the default buffering policy works as follows:
104
105 * Binary files are buffered in fixed-size chunks; the size of the buffer
106 is chosen using a heuristic trying to determine the underlying device's
107 "block size" and falling back on :attr:`DEFAULT_BUFFER_SIZE`.
108 On many systems, the buffer will typically be 4096 or 8192 bytes long.
109
110 * "Interactive" text files (files for which :meth:`isatty` returns True)
111 use line buffering. Other text files use the policy described above
112 for binary files.
Georg Brandl014197c2008-04-09 18:40:51 +0000113
114 *encoding* is the name of the encoding used to decode or encode the file.
Benjamin Petersondd219122008-04-11 21:17:32 +0000115 This should only be used in text mode. The default encoding is platform
Benjamin Peterson52c3bf12009-03-23 02:44:58 +0000116 dependent (whatever :func:`locale.getpreferredencoding` returns), but any
117 encoding supported by Python can be used. See the :mod:`codecs` module for
118 the list of supported encodings.
Georg Brandl014197c2008-04-09 18:40:51 +0000119
Benjamin Petersonb85a5842008-04-13 21:39:58 +0000120 *errors* is an optional string that specifies how encoding and decoding
Benjamin Peterson52c3bf12009-03-23 02:44:58 +0000121 errors are to be handled--this cannot be used in binary mode. Pass
122 ``'strict'`` to raise a :exc:`ValueError` exception if there is an encoding
123 error (the default of ``None`` has the same effect), or pass ``'ignore'`` to
124 ignore errors. (Note that ignoring encoding errors can lead to data loss.)
125 ``'replace'`` causes a replacement marker (such as ``'?'``) to be inserted
126 where there is malformed data. When writing, ``'xmlcharrefreplace'``
127 (replace with the appropriate XML character reference) or
128 ``'backslashreplace'`` (replace with backslashed escape sequences) can be
129 used. Any other error handling name that has been registered with
130 :func:`codecs.register_error` is also valid.
Georg Brandl014197c2008-04-09 18:40:51 +0000131
132 *newline* controls how universal newlines works (it only applies to text
133 mode). It can be ``None``, ``''``, ``'\n'``, ``'\r'``, and ``'\r\n'``. It
134 works as follows:
135
136 * On input, if *newline* is ``None``, universal newlines mode is enabled.
137 Lines in the input can end in ``'\n'``, ``'\r'``, or ``'\r\n'``, and these
138 are translated into ``'\n'`` before being returned to the caller. If it is
139 ``''``, universal newline mode is enabled, but line endings are returned to
140 the caller untranslated. If it has any of the other legal values, input
141 lines are only terminated by the given string, and the line ending is
142 returned to the caller untranslated.
143
144 * On output, if *newline* is ``None``, any ``'\n'`` characters written are
145 translated to the system default line separator, :data:`os.linesep`. If
146 *newline* is ``''``, no translation takes place. If *newline* is any of
147 the other legal values, any ``'\n'`` characters written are translated to
148 the given string.
149
Benjamin Peterson8cad9c72009-03-23 02:38:01 +0000150 If *closefd* is ``False`` and a file descriptor rather than a filename was
151 given, the underlying file descriptor will be kept open when the file is
152 closed. If a filename is given *closefd* has no effect and must be ``True``
153 (the default).
Georg Brandl014197c2008-04-09 18:40:51 +0000154
Georg Brandlc5605df2009-08-13 08:26:44 +0000155 The type of file object returned by the :func:`.open` function depends on the
156 mode. When :func:`.open` is used to open a file in a text mode (``'w'``,
Benjamin Peterson8cad9c72009-03-23 02:38:01 +0000157 ``'r'``, ``'wt'``, ``'rt'``, etc.), it returns a subclass of
158 :class:`TextIOBase` (specifically :class:`TextIOWrapper`). When used to open
159 a file in a binary mode with buffering, the returned class is a subclass of
160 :class:`BufferedIOBase`. The exact class varies: in read binary mode, it
161 returns a :class:`BufferedReader`; in write binary and append binary modes,
162 it returns a :class:`BufferedWriter`, and in read/write mode, it returns a
163 :class:`BufferedRandom`. When buffering is disabled, the raw stream, a
164 subclass of :class:`RawIOBase`, :class:`FileIO`, is returned.
Georg Brandl014197c2008-04-09 18:40:51 +0000165
166 It is also possible to use a string or bytearray as a file for both reading
Benjamin Petersondd219122008-04-11 21:17:32 +0000167 and writing. For strings :class:`StringIO` can be used like a file opened in
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000168 a text mode, and for bytearrays a :class:`BytesIO` can be used like a
169 file opened in a binary mode.
Georg Brandl014197c2008-04-09 18:40:51 +0000170
171
172.. exception:: BlockingIOError
173
174 Error raised when blocking would occur on a non-blocking stream. It inherits
175 :exc:`IOError`.
176
177 In addition to those of :exc:`IOError`, :exc:`BlockingIOError` has one
178 attribute:
179
180 .. attribute:: characters_written
181
182 An integer containing the number of characters written to the stream
183 before it blocked.
184
185
186.. exception:: UnsupportedOperation
187
188 An exception inheriting :exc:`IOError` and :exc:`ValueError` that is raised
189 when an unsupported operation is called on a stream.
190
191
192I/O Base Classes
193----------------
194
195.. class:: IOBase
196
197 The abstract base class for all I/O classes, acting on streams of bytes.
198 There is no public constructor.
199
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000200 This class provides empty abstract implementations for many methods
201 that derived classes can override selectively; the default
202 implementations represent a file that cannot be read, written or
203 seeked.
Georg Brandl014197c2008-04-09 18:40:51 +0000204
205 Even though :class:`IOBase` does not declare :meth:`read`, :meth:`readinto`,
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000206 or :meth:`write` because their signatures will vary, implementations and
207 clients should consider those methods part of the interface. Also,
208 implementations may raise a :exc:`IOError` when operations they do not
209 support are called.
Georg Brandl014197c2008-04-09 18:40:51 +0000210
211 The basic type used for binary data read from or written to a file is
212 :class:`bytes`. :class:`bytearray`\s are accepted too, and in some cases
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000213 (such as :class:`readinto`) required. Text I/O classes work with
214 :class:`str` data.
Georg Brandl014197c2008-04-09 18:40:51 +0000215
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000216 Note that calling any method (even inquiries) on a closed stream is
217 undefined. Implementations may raise :exc:`IOError` in this case.
Georg Brandl014197c2008-04-09 18:40:51 +0000218
219 IOBase (and its subclasses) support the iterator protocol, meaning that an
220 :class:`IOBase` object can be iterated over yielding the lines in a stream.
Antoine Pitrou56abc1f2009-09-17 17:25:55 +0000221 Lines are defined slightly differently depending on whether the stream is
222 a binary stream (yielding bytes), or a text stream (yielding character
223 strings). See :meth:`readline` below.
Georg Brandl014197c2008-04-09 18:40:51 +0000224
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000225 IOBase is also a context manager and therefore supports the
226 :keyword:`with` statement. In this example, *file* is closed after the
227 :keyword:`with` statement's suite is finished---even if an exception occurs::
Georg Brandl014197c2008-04-09 18:40:51 +0000228
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000229 with open('spam.txt', 'w') as file:
230 file.write('Spam and eggs!')
Georg Brandl014197c2008-04-09 18:40:51 +0000231
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000232 :class:`IOBase` provides these data attributes and methods:
Georg Brandl014197c2008-04-09 18:40:51 +0000233
234 .. method:: close()
235
Christian Heimesecc42a22008-11-05 19:30:32 +0000236 Flush and close this stream. This method has no effect if the file is
Georg Brandl48310cd2009-01-03 21:18:54 +0000237 already closed. Once the file is closed, any operation on the file
Georg Brandl6c8583f2010-05-19 21:22:58 +0000238 (e.g. reading or writing) will raise a :exc:`ValueError`.
Antoine Pitroubf539122010-04-28 20:03:21 +0000239
240 As a convenience, it is allowed to call this method more than once;
241 only the first call, however, will have an effect.
Georg Brandl014197c2008-04-09 18:40:51 +0000242
243 .. attribute:: closed
244
245 True if the stream is closed.
246
247 .. method:: fileno()
248
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000249 Return the underlying file descriptor (an integer) of the stream if it
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000250 exists. An :exc:`IOError` is raised if the IO object does not use a file
Georg Brandl014197c2008-04-09 18:40:51 +0000251 descriptor.
252
253 .. method:: flush()
254
Benjamin Petersonb85a5842008-04-13 21:39:58 +0000255 Flush the write buffers of the stream if applicable. This does nothing
256 for read-only and non-blocking streams.
Georg Brandl014197c2008-04-09 18:40:51 +0000257
258 .. method:: isatty()
259
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000260 Return ``True`` if the stream is interactive (i.e., connected to
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000261 a terminal/tty device).
Georg Brandl014197c2008-04-09 18:40:51 +0000262
263 .. method:: readable()
264
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000265 Return ``True`` if the stream can be read from. If False, :meth:`read`
266 will raise :exc:`IOError`.
Georg Brandl014197c2008-04-09 18:40:51 +0000267
Georg Brandl3dd33882009-06-01 17:35:27 +0000268 .. method:: readline(limit=-1)
Georg Brandl014197c2008-04-09 18:40:51 +0000269
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000270 Read and return one line from the stream. If *limit* is specified, at
271 most *limit* bytes will be read.
Georg Brandl014197c2008-04-09 18:40:51 +0000272
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000273 The line terminator is always ``b'\n'`` for binary files; for text files,
Georg Brandlc5605df2009-08-13 08:26:44 +0000274 the *newlines* argument to :func:`.open` can be used to select the line
Georg Brandl014197c2008-04-09 18:40:51 +0000275 terminator(s) recognized.
276
Georg Brandl3dd33882009-06-01 17:35:27 +0000277 .. method:: readlines(hint=-1)
Georg Brandl014197c2008-04-09 18:40:51 +0000278
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000279 Read and return a list of lines from the stream. *hint* can be specified
280 to control the number of lines read: no more lines will be read if the
281 total size (in bytes/characters) of all lines so far exceeds *hint*.
Georg Brandl014197c2008-04-09 18:40:51 +0000282
Georg Brandl3dd33882009-06-01 17:35:27 +0000283 .. method:: seek(offset, whence=SEEK_SET)
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000284
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000285 Change the stream position to the given byte *offset*. *offset* is
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000286 interpreted relative to the position indicated by *whence*. Values for
287 *whence* are:
288
Benjamin Peterson0e4caf42009-04-01 21:22:20 +0000289 * :data:`SEEK_SET` or ``0`` -- start of the stream (the default);
290 *offset* should be zero or positive
291 * :data:`SEEK_CUR` or ``1`` -- current stream position; *offset* may
292 be negative
293 * :data:`SEEK_END` or ``2`` -- end of the stream; *offset* is usually
294 negative
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000295
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000296 Return the new absolute position.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000297
Raymond Hettinger35a88362009-04-09 00:08:24 +0000298 .. versionadded:: 3.1
Benjamin Peterson0e4caf42009-04-01 21:22:20 +0000299 The ``SEEK_*`` constants
300
Georg Brandl014197c2008-04-09 18:40:51 +0000301 .. method:: seekable()
302
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000303 Return ``True`` if the stream supports random access. If ``False``,
304 :meth:`seek`, :meth:`tell` and :meth:`truncate` will raise :exc:`IOError`.
Georg Brandl014197c2008-04-09 18:40:51 +0000305
306 .. method:: tell()
307
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000308 Return the current stream position.
Georg Brandl014197c2008-04-09 18:40:51 +0000309
Georg Brandl3dd33882009-06-01 17:35:27 +0000310 .. method:: truncate(size=None)
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000311
Antoine Pitrouea2b0b42010-05-29 12:10:15 +0000312 Resize the stream to the given *size* in bytes (or the current position
313 if *size* is not specified). The current stream position isn't changed.
314 This resizing can extend or reduce the current file size. In case of
315 extension, the contents of the new file area depend on the platform
316 (on most systems, additional bytes are zero-filled, on Windows they're
317 undetermined). The new file size is returned.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000318
Georg Brandl014197c2008-04-09 18:40:51 +0000319 .. method:: writable()
320
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000321 Return ``True`` if the stream supports writing. If ``False``,
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000322 :meth:`write` and :meth:`truncate` will raise :exc:`IOError`.
Georg Brandl014197c2008-04-09 18:40:51 +0000323
324 .. method:: writelines(lines)
325
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000326 Write a list of lines to the stream. Line separators are not added, so it
327 is usual for each of the lines provided to have a line separator at the
328 end.
Georg Brandl014197c2008-04-09 18:40:51 +0000329
330
331.. class:: RawIOBase
332
333 Base class for raw binary I/O. It inherits :class:`IOBase`. There is no
334 public constructor.
335
Antoine Pitrou56abc1f2009-09-17 17:25:55 +0000336 Raw binary I/O typically provides low-level access to an underlying OS
337 device or API, and does not try to encapsulate it in high-level primitives
338 (this is left to Buffered I/O and Text I/O, described later in this page).
339
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000340 In addition to the attributes and methods from :class:`IOBase`,
341 RawIOBase provides the following methods:
Georg Brandl014197c2008-04-09 18:40:51 +0000342
Georg Brandl3dd33882009-06-01 17:35:27 +0000343 .. method:: read(n=-1)
Georg Brandl014197c2008-04-09 18:40:51 +0000344
Antoine Pitroubd2a68d2009-10-01 16:27:13 +0000345 Read up to *n* bytes from the object and return them. As a convenience,
346 if *n* is unspecified or -1, :meth:`readall` is called. Otherwise,
347 only one system call is ever made. Fewer than *n* bytes may be
348 returned if the operating system call returns fewer than *n* bytes.
349
350 If 0 bytes are returned, and *n* was not 0, this indicates end of file.
351 If the object is in non-blocking mode and no bytes are available,
352 ``None`` is returned.
Georg Brandl014197c2008-04-09 18:40:51 +0000353
Benjamin Petersonb47aace2008-04-09 21:38:38 +0000354 .. method:: readall()
Georg Brandl014197c2008-04-09 18:40:51 +0000355
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000356 Read and return all the bytes from the stream until EOF, using multiple
357 calls to the stream if necessary.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000358
359 .. method:: readinto(b)
360
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000361 Read up to len(b) bytes into bytearray *b* and return the number of bytes
362 read.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000363
364 .. method:: write(b)
365
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000366 Write the given bytes or bytearray object, *b*, to the underlying raw
Antoine Pitrou56abc1f2009-09-17 17:25:55 +0000367 stream and return the number of bytes written. This can be less than
368 ``len(b)``, depending on specifics of the underlying raw stream, and
369 especially if it is in non-blocking mode. ``None`` is returned if the
370 raw stream is set not to block and no single byte could be readily
371 written to it.
Georg Brandl014197c2008-04-09 18:40:51 +0000372
373
Georg Brandl014197c2008-04-09 18:40:51 +0000374.. class:: BufferedIOBase
375
Antoine Pitrou56abc1f2009-09-17 17:25:55 +0000376 Base class for binary streams that support some kind of buffering.
377 It inherits :class:`IOBase`. There is no public constructor.
Georg Brandl014197c2008-04-09 18:40:51 +0000378
Antoine Pitrou56abc1f2009-09-17 17:25:55 +0000379 The main difference with :class:`RawIOBase` is that methods :meth:`read`,
380 :meth:`readinto` and :meth:`write` will try (respectively) to read as much
381 input as requested or to consume all given output, at the expense of
382 making perhaps more than one system call.
383
384 In addition, those methods can raise :exc:`BlockingIOError` if the
385 underlying raw stream is in non-blocking mode and cannot take or give
386 enough data; unlike their :class:`RawIOBase` counterparts, they will
387 never return ``None``.
388
389 Besides, the :meth:`read` method does not have a default
Georg Brandl014197c2008-04-09 18:40:51 +0000390 implementation that defers to :meth:`readinto`.
391
Antoine Pitrou56abc1f2009-09-17 17:25:55 +0000392 A typical :class:`BufferedIOBase` implementation should not inherit from a
393 :class:`RawIOBase` implementation, but wrap one, like
394 :class:`BufferedWriter` and :class:`BufferedReader` do.
Georg Brandl014197c2008-04-09 18:40:51 +0000395
Benjamin Petersond76c8da2009-06-28 17:35:48 +0000396 :class:`BufferedIOBase` provides or overrides these members in addition to
Georg Brandl014197c2008-04-09 18:40:51 +0000397 those from :class:`IOBase`:
398
Benjamin Petersond76c8da2009-06-28 17:35:48 +0000399 .. attribute:: raw
400
401 The underlying raw stream (a :class:`RawIOBase` instance) that
402 :class:`BufferedIOBase` deals with. This is not part of the
403 :class:`BufferedIOBase` API and may not exist on some implementations.
404
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000405 .. method:: detach()
406
407 Separate the underlying raw stream from the buffer and return it.
408
409 After the raw stream has been detached, the buffer is in an unusable
410 state.
411
412 Some buffers, like :class:`BytesIO`, do not have the concept of a single
413 raw stream to return from this method. They raise
414 :exc:`UnsupportedOperation`.
415
Benjamin Petersonedc36472009-05-01 20:48:14 +0000416 .. versionadded:: 3.1
417
Georg Brandl3dd33882009-06-01 17:35:27 +0000418 .. method:: read(n=-1)
Georg Brandl014197c2008-04-09 18:40:51 +0000419
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000420 Read and return up to *n* bytes. If the argument is omitted, ``None``, or
Georg Brandl014197c2008-04-09 18:40:51 +0000421 negative, data is read and returned until EOF is reached. An empty bytes
422 object is returned if the stream is already at EOF.
423
424 If the argument is positive, and the underlying raw stream is not
425 interactive, multiple raw reads may be issued to satisfy the byte count
426 (unless EOF is reached first). But for interactive raw streams, at most
427 one raw read will be issued, and a short result does not imply that EOF is
428 imminent.
429
Antoine Pitrou56abc1f2009-09-17 17:25:55 +0000430 A :exc:`BlockingIOError` is raised if the underlying raw stream is in
431 non blocking-mode, and has no data available at the moment.
Georg Brandl014197c2008-04-09 18:40:51 +0000432
Georg Brandl3dd33882009-06-01 17:35:27 +0000433 .. method:: read1(n=-1)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000434
435 Read and return up to *n* bytes, with at most one call to the underlying
Antoine Pitrou56abc1f2009-09-17 17:25:55 +0000436 raw stream's :meth:`~RawIOBase.read` method. This can be useful if you
437 are implementing your own buffering on top of a :class:`BufferedIOBase`
438 object.
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000439
Georg Brandl014197c2008-04-09 18:40:51 +0000440 .. method:: readinto(b)
441
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000442 Read up to len(b) bytes into bytearray *b* and return the number of bytes
Georg Brandl014197c2008-04-09 18:40:51 +0000443 read.
444
445 Like :meth:`read`, multiple reads may be issued to the underlying raw
Antoine Pitrou56abc1f2009-09-17 17:25:55 +0000446 stream, unless the latter is 'interactive'.
Georg Brandl014197c2008-04-09 18:40:51 +0000447
Antoine Pitrou56abc1f2009-09-17 17:25:55 +0000448 A :exc:`BlockingIOError` is raised if the underlying raw stream is in
449 non blocking-mode, and has no data available at the moment.
Georg Brandl014197c2008-04-09 18:40:51 +0000450
Georg Brandl014197c2008-04-09 18:40:51 +0000451 .. method:: write(b)
452
Antoine Pitrou56abc1f2009-09-17 17:25:55 +0000453 Write the given bytes or bytearray object, *b* and return the number
454 of bytes written (never less than ``len(b)``, since if the write fails
455 an :exc:`IOError` will be raised). Depending on the actual
456 implementation, these bytes may be readily written to the underlying
457 stream, or held in a buffer for performance and latency reasons.
Georg Brandl014197c2008-04-09 18:40:51 +0000458
Antoine Pitrou56abc1f2009-09-17 17:25:55 +0000459 When in non-blocking mode, a :exc:`BlockingIOError` is raised if the
460 data needed to be written to the raw stream but it couldn't accept
461 all the data without blocking.
Georg Brandl014197c2008-04-09 18:40:51 +0000462
463
Benjamin Petersonaa069002009-01-23 03:26:36 +0000464Raw File I/O
465------------
466
Georg Brandl3dd33882009-06-01 17:35:27 +0000467.. class:: FileIO(name, mode='r', closefd=True)
Benjamin Petersonaa069002009-01-23 03:26:36 +0000468
Antoine Pitrou56abc1f2009-09-17 17:25:55 +0000469 :class:`FileIO` represents an OS-level file containing bytes data.
470 It implements the :class:`RawIOBase` interface (and therefore the
471 :class:`IOBase` interface, too).
472
473 The *name* can be one of two things:
474
475 * a character string or bytes object representing the path to the file
476 which will be opened;
477 * an integer representing the number of an existing OS-level file descriptor
478 to which the resulting :class:`FileIO` object will give access.
Benjamin Petersonaa069002009-01-23 03:26:36 +0000479
480 The *mode* can be ``'r'``, ``'w'`` or ``'a'`` for reading (default), writing,
481 or appending. The file will be created if it doesn't exist when opened for
482 writing or appending; it will be truncated when opened for writing. Add a
483 ``'+'`` to the mode to allow simultaneous reading and writing.
484
Antoine Pitrou56abc1f2009-09-17 17:25:55 +0000485 The :meth:`read` (when called with a positive argument), :meth:`readinto`
486 and :meth:`write` methods on this class will only make one system call.
487
Benjamin Petersonaa069002009-01-23 03:26:36 +0000488 In addition to the attributes and methods from :class:`IOBase` and
489 :class:`RawIOBase`, :class:`FileIO` provides the following data
490 attributes and methods:
491
492 .. attribute:: mode
493
494 The mode as given in the constructor.
495
496 .. attribute:: name
497
498 The file name. This is the file descriptor of the file when no name is
499 given in the constructor.
500
Benjamin Petersonaa069002009-01-23 03:26:36 +0000501
502Buffered Streams
503----------------
504
Antoine Pitrou56abc1f2009-09-17 17:25:55 +0000505In many situations, buffered I/O streams will provide higher performance
506(bandwidth and latency) than raw I/O streams. Their API is also more usable.
507
Georg Brandl014197c2008-04-09 18:40:51 +0000508.. class:: BytesIO([initial_bytes])
509
510 A stream implementation using an in-memory bytes buffer. It inherits
511 :class:`BufferedIOBase`.
512
513 The argument *initial_bytes* is an optional initial bytearray.
514
515 :class:`BytesIO` provides or overrides these methods in addition to those
516 from :class:`BufferedIOBase` and :class:`IOBase`:
517
518 .. method:: getvalue()
519
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000520 Return ``bytes`` containing the entire contents of the buffer.
Georg Brandl014197c2008-04-09 18:40:51 +0000521
522 .. method:: read1()
523
Benjamin Peterson9efcc4b2008-04-14 21:30:21 +0000524 In :class:`BytesIO`, this is the same as :meth:`read`.
Georg Brandl014197c2008-04-09 18:40:51 +0000525
Georg Brandl014197c2008-04-09 18:40:51 +0000526
Georg Brandl3dd33882009-06-01 17:35:27 +0000527.. class:: BufferedReader(raw, buffer_size=DEFAULT_BUFFER_SIZE)
Georg Brandl014197c2008-04-09 18:40:51 +0000528
Antoine Pitrou56abc1f2009-09-17 17:25:55 +0000529 A buffer providing higher-level access to a readable, sequential
530 :class:`RawIOBase` object. It inherits :class:`BufferedIOBase`.
531 When reading data from this object, a larger amount of data may be
532 requested from the underlying raw stream, and kept in an internal buffer.
533 The buffered data can then be returned directly on subsequent reads.
Georg Brandl014197c2008-04-09 18:40:51 +0000534
535 The constructor creates a :class:`BufferedReader` for the given readable
536 *raw* stream and *buffer_size*. If *buffer_size* is omitted,
537 :data:`DEFAULT_BUFFER_SIZE` is used.
538
539 :class:`BufferedReader` provides or overrides these methods in addition to
540 those from :class:`BufferedIOBase` and :class:`IOBase`:
541
542 .. method:: peek([n])
543
Benjamin Petersonc43a26d2009-06-16 23:09:24 +0000544 Return bytes from the stream without advancing the position. At most one
Benjamin Peterson2a8b54d2009-06-14 14:37:23 +0000545 single read on the raw stream is done to satisfy the call. The number of
546 bytes returned may be less or more than requested.
Georg Brandl014197c2008-04-09 18:40:51 +0000547
548 .. method:: read([n])
549
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000550 Read and return *n* bytes, or if *n* is not given or negative, until EOF
Georg Brandl014197c2008-04-09 18:40:51 +0000551 or if the read call would block in non-blocking mode.
552
553 .. method:: read1(n)
554
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000555 Read and return up to *n* bytes with only one call on the raw stream. If
Georg Brandl014197c2008-04-09 18:40:51 +0000556 at least one byte is buffered, only buffered bytes are returned.
557 Otherwise, one raw stream read call is made.
558
559
Georg Brandl3dd33882009-06-01 17:35:27 +0000560.. class:: BufferedWriter(raw, buffer_size=DEFAULT_BUFFER_SIZE)
Georg Brandl014197c2008-04-09 18:40:51 +0000561
Antoine Pitrou56abc1f2009-09-17 17:25:55 +0000562 A buffer providing higher-level access to a writeable, sequential
563 :class:`RawIOBase` object. It inherits :class:`BufferedIOBase`.
564 When writing to this object, data is normally held into an internal
565 buffer. The buffer will be written out to the underlying :class:`RawIOBase`
566 object under various conditions, including:
567
568 * when the buffer gets too small for all pending data;
569 * when :meth:`flush()` is called;
570 * when a :meth:`seek()` is requested (for :class:`BufferedRandom` objects);
571 * when the :class:`BufferedWriter` object is closed or destroyed.
Georg Brandl014197c2008-04-09 18:40:51 +0000572
573 The constructor creates a :class:`BufferedWriter` for the given writeable
574 *raw* stream. If the *buffer_size* is not given, it defaults to
Benjamin Peterson394ee002009-03-05 22:33:59 +0000575 :data:`DEFAULT_BUFFER_SIZE`.
576
Georg Brandl3dd33882009-06-01 17:35:27 +0000577 A third argument, *max_buffer_size*, is supported, but unused and deprecated.
Georg Brandl014197c2008-04-09 18:40:51 +0000578
579 :class:`BufferedWriter` provides or overrides these methods in addition to
580 those from :class:`BufferedIOBase` and :class:`IOBase`:
581
582 .. method:: flush()
583
584 Force bytes held in the buffer into the raw stream. A
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000585 :exc:`BlockingIOError` should be raised if the raw stream blocks.
Georg Brandl014197c2008-04-09 18:40:51 +0000586
587 .. method:: write(b)
588
Antoine Pitrou56abc1f2009-09-17 17:25:55 +0000589 Write the bytes or bytearray object, *b* and return the number of bytes
590 written. When in non-blocking mode, a :exc:`BlockingIOError` is raised
591 if the buffer needs to be written out but the raw stream blocks.
Georg Brandl014197c2008-04-09 18:40:51 +0000592
593
Antoine Pitrou56abc1f2009-09-17 17:25:55 +0000594.. class:: BufferedRWPair(reader, writer, buffer_size=DEFAULT_BUFFER_SIZE)
Georg Brandl014197c2008-04-09 18:40:51 +0000595
Antoine Pitrou56abc1f2009-09-17 17:25:55 +0000596 A buffered I/O object giving a combined, higher-level access to two
597 sequential :class:`RawIOBase` objects: one readable, the other writeable.
598 It is useful for pairs of unidirectional communication channels
599 (pipes, for instance). It inherits :class:`BufferedIOBase`.
Georg Brandl014197c2008-04-09 18:40:51 +0000600
601 *reader* and *writer* are :class:`RawIOBase` objects that are readable and
602 writeable respectively. If the *buffer_size* is omitted it defaults to
Benjamin Peterson394ee002009-03-05 22:33:59 +0000603 :data:`DEFAULT_BUFFER_SIZE`.
604
Georg Brandl3dd33882009-06-01 17:35:27 +0000605 A fourth argument, *max_buffer_size*, is supported, but unused and
606 deprecated.
Georg Brandl014197c2008-04-09 18:40:51 +0000607
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000608 :class:`BufferedRWPair` implements all of :class:`BufferedIOBase`\'s methods
609 except for :meth:`~BufferedIOBase.detach`, which raises
610 :exc:`UnsupportedOperation`.
Georg Brandl014197c2008-04-09 18:40:51 +0000611
612
Georg Brandl3dd33882009-06-01 17:35:27 +0000613.. class:: BufferedRandom(raw, buffer_size=DEFAULT_BUFFER_SIZE)
Georg Brandl014197c2008-04-09 18:40:51 +0000614
615 A buffered interface to random access streams. It inherits
Antoine Pitrou56abc1f2009-09-17 17:25:55 +0000616 :class:`BufferedReader` and :class:`BufferedWriter`, and further supports
617 :meth:`seek` and :meth:`tell` functionality.
Georg Brandl014197c2008-04-09 18:40:51 +0000618
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000619 The constructor creates a reader and writer for a seekable raw stream, given
Georg Brandl014197c2008-04-09 18:40:51 +0000620 in the first argument. If the *buffer_size* is omitted it defaults to
Benjamin Peterson394ee002009-03-05 22:33:59 +0000621 :data:`DEFAULT_BUFFER_SIZE`.
622
Georg Brandl3dd33882009-06-01 17:35:27 +0000623 A third argument, *max_buffer_size*, is supported, but unused and deprecated.
Georg Brandl014197c2008-04-09 18:40:51 +0000624
625 :class:`BufferedRandom` is capable of anything :class:`BufferedReader` or
626 :class:`BufferedWriter` can do.
627
628
629Text I/O
630--------
631
632.. class:: TextIOBase
633
634 Base class for text streams. This class provides a character and line based
635 interface to stream I/O. There is no :meth:`readinto` method because
636 Python's character strings are immutable. It inherits :class:`IOBase`.
637 There is no public constructor.
638
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000639 :class:`TextIOBase` provides or overrides these data attributes and
640 methods in addition to those from :class:`IOBase`:
Georg Brandl014197c2008-04-09 18:40:51 +0000641
642 .. attribute:: encoding
643
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000644 The name of the encoding used to decode the stream's bytes into
Georg Brandl014197c2008-04-09 18:40:51 +0000645 strings, and to encode strings into bytes.
646
Benjamin Peterson0926ad12009-06-06 18:02:12 +0000647 .. attribute:: errors
648
649 The error setting of the decoder or encoder.
650
Georg Brandl014197c2008-04-09 18:40:51 +0000651 .. attribute:: newlines
652
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000653 A string, a tuple of strings, or ``None``, indicating the newlines
Antoine Pitrou56abc1f2009-09-17 17:25:55 +0000654 translated so far. Depending on the implementation and the initial
655 constructor flags, this may not be available.
Georg Brandl014197c2008-04-09 18:40:51 +0000656
Benjamin Petersond76c8da2009-06-28 17:35:48 +0000657 .. attribute:: buffer
658
659 The underlying binary buffer (a :class:`BufferedIOBase` instance) that
660 :class:`TextIOBase` deals with. This is not part of the
661 :class:`TextIOBase` API and may not exist on some implementations.
662
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000663 .. method:: detach()
664
Antoine Pitrou56abc1f2009-09-17 17:25:55 +0000665 Separate the underlying binary buffer from the :class:`TextIOBase` and
666 return it.
Benjamin Petersond2e0c792009-05-01 20:40:59 +0000667
668 After the underlying buffer has been detached, the :class:`TextIOBase` is
669 in an unusable state.
670
671 Some :class:`TextIOBase` implementations, like :class:`StringIO`, may not
672 have the concept of an underlying buffer and calling this method will
673 raise :exc:`UnsupportedOperation`.
674
Benjamin Petersonedc36472009-05-01 20:48:14 +0000675 .. versionadded:: 3.1
676
Georg Brandl014197c2008-04-09 18:40:51 +0000677 .. method:: read(n)
678
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000679 Read and return at most *n* characters from the stream as a single
Antoine Pitrou56abc1f2009-09-17 17:25:55 +0000680 :class:`str`. If *n* is negative or ``None``, reads until EOF.
Georg Brandl014197c2008-04-09 18:40:51 +0000681
682 .. method:: readline()
683
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000684 Read until newline or EOF and return a single ``str``. If the stream is
685 already at EOF, an empty string is returned.
Georg Brandl014197c2008-04-09 18:40:51 +0000686
Georg Brandl014197c2008-04-09 18:40:51 +0000687 .. method:: write(s)
688
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000689 Write the string *s* to the stream and return the number of characters
690 written.
Georg Brandl014197c2008-04-09 18:40:51 +0000691
692
Georg Brandl3dd33882009-06-01 17:35:27 +0000693.. class:: TextIOWrapper(buffer, encoding=None, errors=None, newline=None, line_buffering=False)
Georg Brandl014197c2008-04-09 18:40:51 +0000694
Antoine Pitrou56abc1f2009-09-17 17:25:55 +0000695 A buffered text stream over a :class:`BufferedIOBase` binary stream.
Georg Brandl014197c2008-04-09 18:40:51 +0000696 It inherits :class:`TextIOBase`.
697
698 *encoding* gives the name of the encoding that the stream will be decoded or
699 encoded with. It defaults to :func:`locale.getpreferredencoding`.
700
Benjamin Petersonb85a5842008-04-13 21:39:58 +0000701 *errors* is an optional string that specifies how encoding and decoding
702 errors are to be handled. Pass ``'strict'`` to raise a :exc:`ValueError`
703 exception if there is an encoding error (the default of ``None`` has the same
704 effect), or pass ``'ignore'`` to ignore errors. (Note that ignoring encoding
705 errors can lead to data loss.) ``'replace'`` causes a replacement marker
Christian Heimesa342c012008-04-20 21:01:16 +0000706 (such as ``'?'``) to be inserted where there is malformed data. When
707 writing, ``'xmlcharrefreplace'`` (replace with the appropriate XML character
708 reference) or ``'backslashreplace'`` (replace with backslashed escape
709 sequences) can be used. Any other error handling name that has been
710 registered with :func:`codecs.register_error` is also valid.
Georg Brandl014197c2008-04-09 18:40:51 +0000711
712 *newline* can be ``None``, ``''``, ``'\n'``, ``'\r'``, or ``'\r\n'``. It
713 controls the handling of line endings. If it is ``None``, universal newlines
714 is enabled. With this enabled, on input, the lines endings ``'\n'``,
715 ``'\r'``, or ``'\r\n'`` are translated to ``'\n'`` before being returned to
716 the caller. Conversely, on output, ``'\n'`` is translated to the system
Mark Dickinson934896d2009-02-21 20:59:32 +0000717 default line separator, :data:`os.linesep`. If *newline* is any other of its
Georg Brandl014197c2008-04-09 18:40:51 +0000718 legal values, that newline becomes the newline when the file is read and it
719 is returned untranslated. On output, ``'\n'`` is converted to the *newline*.
720
721 If *line_buffering* is ``True``, :meth:`flush` is implied when a call to
722 write contains a newline character.
723
Benjamin Peterson0926ad12009-06-06 18:02:12 +0000724 :class:`TextIOWrapper` provides one attribute in addition to those of
Georg Brandl014197c2008-04-09 18:40:51 +0000725 :class:`TextIOBase` and its parents:
726
Georg Brandl014197c2008-04-09 18:40:51 +0000727 .. attribute:: line_buffering
728
729 Whether line buffering is enabled.
Georg Brandl48310cd2009-01-03 21:18:54 +0000730
Georg Brandl014197c2008-04-09 18:40:51 +0000731
Georg Brandl3dd33882009-06-01 17:35:27 +0000732.. class:: StringIO(initial_value='', newline=None)
Georg Brandl014197c2008-04-09 18:40:51 +0000733
Georg Brandl2932d932008-05-30 06:27:09 +0000734 An in-memory stream for text. It inherits :class:`TextIOWrapper`.
Georg Brandl014197c2008-04-09 18:40:51 +0000735
Benjamin Petersonaa1c8d82009-03-09 02:02:23 +0000736 The initial value of the buffer (an empty string by default) can be set by
737 providing *initial_value*. The *newline* argument works like that of
738 :class:`TextIOWrapper`. The default is to do no newline translation.
Georg Brandl014197c2008-04-09 18:40:51 +0000739
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000740 :class:`StringIO` provides this method in addition to those from
Georg Brandl014197c2008-04-09 18:40:51 +0000741 :class:`TextIOWrapper` and its parents:
742
743 .. method:: getvalue()
744
Georg Brandl2932d932008-05-30 06:27:09 +0000745 Return a ``str`` containing the entire contents of the buffer at any
746 time before the :class:`StringIO` object's :meth:`close` method is
747 called.
Georg Brandl014197c2008-04-09 18:40:51 +0000748
Georg Brandl2932d932008-05-30 06:27:09 +0000749 Example usage::
750
751 import io
752
753 output = io.StringIO()
754 output.write('First line.\n')
755 print('Second line.', file=output)
756
757 # Retrieve file contents -- this will be
758 # 'First line.\nSecond line.\n'
759 contents = output.getvalue()
760
Georg Brandl48310cd2009-01-03 21:18:54 +0000761 # Close object and discard memory buffer --
Georg Brandl2932d932008-05-30 06:27:09 +0000762 # .getvalue() will now raise an exception.
763 output.close()
Georg Brandl014197c2008-04-09 18:40:51 +0000764
765.. class:: IncrementalNewlineDecoder
766
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000767 A helper codec that decodes newlines for universal newlines mode. It
768 inherits :class:`codecs.IncrementalDecoder`.
Georg Brandl014197c2008-04-09 18:40:51 +0000769