blob: cf5e9f766d2179ce88963d824fd7495b15234a88 [file] [log] [blame]
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +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>
Antoine Pitrouc9062ca2009-10-01 17:08:03 +00009.. moduleauthor:: Antoine Pitrou <solipsis@pitrou.net>
10.. moduleauthor:: Amaury Forgeot d'Arc <amauryfa@gmail.com>
11.. moduleauthor:: Benjamin Peterson <benjamin@python.org>
Benjamin Peterson51a37032009-01-11 19:48:15 +000012.. sectionauthor:: Benjamin Peterson <benjamin@python.org>
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +000013
Antoine Pitrouc9062ca2009-10-01 17:08:03 +000014The :mod:`io` module provides the Python interfaces to stream handling.
15Under Python 2.x, this is proposed as an alternative to the built-in
16:class:`file` object, but in Python 3.x it is the default interface to
17access files and streams.
18
19.. note::
20
21 Since this module has been designed primarily for Python 3.x, you have to
22 be aware that all uses of "bytes" in this document refer to the
23 :class:`str` type (of which :class:`bytes` is an alias), and all uses
24 of "text" refer to the :class:`unicode` type. Furthermore, those two
25 types are not interchangeable in the :mod:`io` APIs.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +000026
27At the top of the I/O hierarchy is the abstract base class :class:`IOBase`. It
28defines the basic interface to a stream. Note, however, that there is no
Mark Dickinson3e4caeb2009-02-21 20:27:01 +000029separation between reading and writing to streams; implementations are allowed
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +000030to throw an :exc:`IOError` if they do not support a given operation.
31
32Extending :class:`IOBase` is :class:`RawIOBase` which deals simply with the
33reading and writing of raw bytes to a stream. :class:`FileIO` subclasses
Benjamin Petersonad9f6292008-04-21 11:57:40 +000034:class:`RawIOBase` to provide an interface to files in the machine's
35file system.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +000036
37:class:`BufferedIOBase` deals with buffering on a raw byte stream
38(:class:`RawIOBase`). Its subclasses, :class:`BufferedWriter`,
39:class:`BufferedReader`, and :class:`BufferedRWPair` buffer streams that are
Benjamin Petersonad9f6292008-04-21 11:57:40 +000040readable, writable, and both readable and writable.
41:class:`BufferedRandom` provides a buffered interface to random access
42streams. :class:`BytesIO` is a simple stream of in-memory bytes.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +000043
Benjamin Petersonad9f6292008-04-21 11:57:40 +000044Another :class:`IOBase` subclass, :class:`TextIOBase`, deals with
45streams whose bytes represent text, and handles encoding and decoding
Antoine Pitrouc9062ca2009-10-01 17:08:03 +000046from and to :class:`unicode` strings. :class:`TextIOWrapper`, which extends
47it, is a buffered text interface to a buffered raw stream
Benjamin Petersonad9f6292008-04-21 11:57:40 +000048(:class:`BufferedIOBase`). Finally, :class:`StringIO` is an in-memory
Antoine Pitrouc9062ca2009-10-01 17:08:03 +000049stream for unicode text.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +000050
51Argument names are not part of the specification, and only the arguments of
Georg Brandl9fa61bb2009-07-26 14:19:57 +000052:func:`.open` are intended to be used as keyword arguments.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +000053
54
55Module Interface
56----------------
57
58.. data:: DEFAULT_BUFFER_SIZE
59
60 An int containing the default buffer size used by the module's buffered I/O
Georg Brandl9fa61bb2009-07-26 14:19:57 +000061 classes. :func:`.open` uses the file's blksize (as obtained by
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +000062 :func:`os.stat`) if possible.
63
Benjamin Petersona9bd6d52010-04-27 21:01:54 +000064.. function:: open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True)
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +000065
Antoine Pitrouc9062ca2009-10-01 17:08:03 +000066 Open *file* and return a corresponding stream. If the file cannot be opened,
67 an :exc:`IOError` is raised.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +000068
Antoine Pitrouc9062ca2009-10-01 17:08:03 +000069 *file* is either a string giving the name (and the path if the file isn't
70 in the current working directory) of the file to be opened or an integer
71 file descriptor of the file to be wrapped. (If a file descriptor is given,
72 for example, from :func:`os.fdopen`, it is closed when the returned I/O
73 object is closed, unless *closefd* is set to ``False``.)
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +000074
75 *mode* is an optional string that specifies the mode in which the file is
76 opened. It defaults to ``'r'`` which means open for reading in text mode.
77 Other common values are ``'w'`` for writing (truncating the file if it
78 already exists), and ``'a'`` for appending (which on *some* Unix systems,
79 means that *all* writes append to the end of the file regardless of the
80 current seek position). In text mode, if *encoding* is not specified the
81 encoding used is platform dependent. (For reading and writing raw bytes use
82 binary mode and leave *encoding* unspecified.) The available modes are:
83
84 ========= ===============================================================
85 Character Meaning
86 --------- ---------------------------------------------------------------
87 ``'r'`` open for reading (default)
88 ``'w'`` open for writing, truncating the file first
89 ``'a'`` open for writing, appending to the end of the file if it exists
90 ``'b'`` binary mode
91 ``'t'`` text mode (default)
92 ``'+'`` open a disk file for updating (reading and writing)
Benjamin Petersonad9f6292008-04-21 11:57:40 +000093 ``'U'`` universal newline mode (for backwards compatibility; should
94 not be used in new code)
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +000095 ========= ===============================================================
96
97 The default mode is ``'rt'`` (open for reading text). For binary random
98 access, the mode ``'w+b'`` opens and truncates the file to 0 bytes, while
99 ``'r+b'`` opens the file without truncation.
100
101 Python distinguishes between files opened in binary and text modes, even when
102 the underlying operating system doesn't. Files opened in binary mode
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000103 (including ``'b'`` in the *mode* argument) return contents as :class:`bytes`
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000104 objects without any decoding. In text mode (the default, or when ``'t'`` is
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000105 included in the *mode* argument), the contents of the file are returned as
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000106 :class:`unicode` strings, the bytes having been first decoded using a
107 platform-dependent encoding or using the specified *encoding* if given.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000108
Antoine Pitroue812d292009-12-19 21:01:10 +0000109 *buffering* is an optional integer used to set the buffering policy.
110 Pass 0 to switch buffering off (only allowed in binary mode), 1 to select
111 line buffering (only usable in text mode), and an integer > 1 to indicate
112 the size of a fixed-size chunk buffer. When no *buffering* argument is
113 given, the default buffering policy works as follows:
114
115 * Binary files are buffered in fixed-size chunks; the size of the buffer
116 is chosen using a heuristic trying to determine the underlying device's
117 "block size" and falling back on :attr:`DEFAULT_BUFFER_SIZE`.
118 On many systems, the buffer will typically be 4096 or 8192 bytes long.
119
120 * "Interactive" text files (files for which :meth:`isatty` returns True)
121 use line buffering. Other text files use the policy described above
122 for binary files.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000123
124 *encoding* is the name of the encoding used to decode or encode the file.
125 This should only be used in text mode. The default encoding is platform
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000126 dependent (whatever :func:`locale.getpreferredencoding` returns), but any
127 encoding supported by Python can be used. See the :mod:`codecs` module for
128 the list of supported encodings.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000129
Benjamin Peterson53be57e2008-04-19 19:34:05 +0000130 *errors* is an optional string that specifies how encoding and decoding
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000131 errors are to be handled--this cannot be used in binary mode. Pass
132 ``'strict'`` to raise a :exc:`ValueError` exception if there is an encoding
133 error (the default of ``None`` has the same effect), or pass ``'ignore'`` to
134 ignore errors. (Note that ignoring encoding errors can lead to data loss.)
135 ``'replace'`` causes a replacement marker (such as ``'?'``) to be inserted
136 where there is malformed data. When writing, ``'xmlcharrefreplace'``
137 (replace with the appropriate XML character reference) or
138 ``'backslashreplace'`` (replace with backslashed escape sequences) can be
139 used. Any other error handling name that has been registered with
140 :func:`codecs.register_error` is also valid.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000141
142 *newline* controls how universal newlines works (it only applies to text
143 mode). It can be ``None``, ``''``, ``'\n'``, ``'\r'``, and ``'\r\n'``. It
144 works as follows:
145
146 * On input, if *newline* is ``None``, universal newlines mode is enabled.
147 Lines in the input can end in ``'\n'``, ``'\r'``, or ``'\r\n'``, and these
148 are translated into ``'\n'`` before being returned to the caller. If it is
149 ``''``, universal newline mode is enabled, but line endings are returned to
150 the caller untranslated. If it has any of the other legal values, input
151 lines are only terminated by the given string, and the line ending is
152 returned to the caller untranslated.
153
154 * On output, if *newline* is ``None``, any ``'\n'`` characters written are
155 translated to the system default line separator, :data:`os.linesep`. If
156 *newline* is ``''``, no translation takes place. If *newline* is any of
157 the other legal values, any ``'\n'`` characters written are translated to
158 the given string.
159
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000160 If *closefd* is ``False`` and a file descriptor rather than a filename was
161 given, the underlying file descriptor will be kept open when the file is
162 closed. If a filename is given *closefd* has no effect and must be ``True``
163 (the default).
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000164
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000165 The type of file object returned by the :func:`.open` function depends on the
166 mode. When :func:`.open` is used to open a file in a text mode (``'w'``,
167 ``'r'``, ``'wt'``, ``'rt'``, etc.), it returns a subclass of
168 :class:`TextIOBase` (specifically :class:`TextIOWrapper`). When used to open
169 a file in a binary mode with buffering, the returned class is a subclass of
170 :class:`BufferedIOBase`. The exact class varies: in read binary mode, it
171 returns a :class:`BufferedReader`; in write binary and append binary modes,
172 it returns a :class:`BufferedWriter`, and in read/write mode, it returns a
173 :class:`BufferedRandom`. When buffering is disabled, the raw stream, a
174 subclass of :class:`RawIOBase`, :class:`FileIO`, is returned.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000175
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000176 It is also possible to use an :class:`unicode` or :class:`bytes` string
177 as a file for both reading and writing. For :class:`unicode` strings
178 :class:`StringIO` can be used like a file opened in text mode,
179 and for :class:`bytes` a :class:`BytesIO` can be used like a
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000180 file opened in a binary mode.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000181
182
183.. exception:: BlockingIOError
184
185 Error raised when blocking would occur on a non-blocking stream. It inherits
186 :exc:`IOError`.
187
188 In addition to those of :exc:`IOError`, :exc:`BlockingIOError` has one
189 attribute:
190
191 .. attribute:: characters_written
192
193 An integer containing the number of characters written to the stream
194 before it blocked.
195
196
197.. exception:: UnsupportedOperation
198
199 An exception inheriting :exc:`IOError` and :exc:`ValueError` that is raised
200 when an unsupported operation is called on a stream.
201
202
203I/O Base Classes
204----------------
205
206.. class:: IOBase
207
208 The abstract base class for all I/O classes, acting on streams of bytes.
209 There is no public constructor.
210
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000211 This class provides empty abstract implementations for many methods
212 that derived classes can override selectively; the default
213 implementations represent a file that cannot be read, written or
214 seeked.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000215
216 Even though :class:`IOBase` does not declare :meth:`read`, :meth:`readinto`,
217 or :meth:`write` because their signatures will vary, implementations and
218 clients should consider those methods part of the interface. Also,
219 implementations may raise a :exc:`IOError` when operations they do not
220 support are called.
221
222 The basic type used for binary data read from or written to a file is
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000223 :class:`bytes` (also known as :class:`str`). :class:`bytearray`\s are
224 accepted too, and in some cases (such as :class:`readinto`) required.
225 Text I/O classes work with :class:`unicode` data.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000226
227 Note that calling any method (even inquiries) on a closed stream is
228 undefined. Implementations may raise :exc:`IOError` in this case.
229
230 IOBase (and its subclasses) support the iterator protocol, meaning that an
231 :class:`IOBase` object can be iterated over yielding the lines in a stream.
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000232 Lines are defined slightly differently depending on whether the stream is
233 a binary stream (yielding :class:`bytes`), or a text stream (yielding
234 :class:`unicode` strings). See :meth:`readline` below.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000235
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000236 IOBase is also a context manager and therefore supports the
237 :keyword:`with` statement. In this example, *file* is closed after the
238 :keyword:`with` statement's suite is finished---even if an exception occurs::
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000239
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000240 with io.open('spam.txt', 'w') as file:
241 file.write(u'Spam and eggs!')
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000242
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000243 :class:`IOBase` provides these data attributes and methods:
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000244
245 .. method:: close()
246
Amaury Forgeot d'Arc32265652008-11-20 23:34:31 +0000247 Flush and close this stream. This method has no effect if the file is
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000248 already closed. Once the file is closed, any operation on the file
Amaury Forgeot d'Arc32265652008-11-20 23:34:31 +0000249 (e.g. reading or writing) will raise an :exc:`IOError`. The internal
250 file descriptor isn't closed if *closefd* was False.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000251
252 .. attribute:: closed
253
254 True if the stream is closed.
255
256 .. method:: fileno()
257
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000258 Return the underlying file descriptor (an integer) of the stream if it
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000259 exists. An :exc:`IOError` is raised if the IO object does not use a file
260 descriptor.
261
262 .. method:: flush()
263
Benjamin Peterson53be57e2008-04-19 19:34:05 +0000264 Flush the write buffers of the stream if applicable. This does nothing
265 for read-only and non-blocking streams.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000266
267 .. method:: isatty()
268
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000269 Return ``True`` if the stream is interactive (i.e., connected to
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000270 a terminal/tty device).
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000271
272 .. method:: readable()
273
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000274 Return ``True`` if the stream can be read from. If False, :meth:`read`
275 will raise :exc:`IOError`.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000276
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000277 .. method:: readline(limit=-1)
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000278
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000279 Read and return one line from the stream. If *limit* is specified, at
280 most *limit* bytes will be read.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000281
282 The line terminator is always ``b'\n'`` for binary files; for text files,
Georg Brandl9fa61bb2009-07-26 14:19:57 +0000283 the *newlines* argument to :func:`.open` can be used to select the line
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000284 terminator(s) recognized.
285
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000286 .. method:: readlines(hint=-1)
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000287
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000288 Read and return a list of lines from the stream. *hint* can be specified
289 to control the number of lines read: no more lines will be read if the
290 total size (in bytes/characters) of all lines so far exceeds *hint*.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000291
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000292 .. method:: seek(offset, whence=SEEK_SET)
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000293
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000294 Change the stream position to the given byte *offset*. *offset* is
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000295 interpreted relative to the position indicated by *whence*. Values for
296 *whence* are:
297
Georg Brandl88ed8f22009-04-01 21:00:55 +0000298 * :data:`SEEK_SET` or ``0`` -- start of the stream (the default);
299 *offset* should be zero or positive
300 * :data:`SEEK_CUR` or ``1`` -- current stream position; *offset* may
301 be negative
302 * :data:`SEEK_END` or ``2`` -- end of the stream; *offset* is usually
303 negative
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000304
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000305 Return the new absolute position.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000306
Georg Brandl88ed8f22009-04-01 21:00:55 +0000307 .. versionadded:: 2.7
308 The ``SEEK_*`` constants
309
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000310 .. method:: seekable()
311
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000312 Return ``True`` if the stream supports random access. If ``False``,
313 :meth:`seek`, :meth:`tell` and :meth:`truncate` will raise :exc:`IOError`.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000314
315 .. method:: tell()
316
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000317 Return the current stream position.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000318
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000319 .. method:: truncate(size=None)
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000320
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000321 Truncate the file to at most *size* bytes. *size* defaults to the current
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000322 file position, as returned by :meth:`tell`.
323
324 .. method:: writable()
325
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000326 Return ``True`` if the stream supports writing. If ``False``,
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000327 :meth:`write` and :meth:`truncate` will raise :exc:`IOError`.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000328
329 .. method:: writelines(lines)
330
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000331 Write a list of lines to the stream. Line separators are not added, so it
332 is usual for each of the lines provided to have a line separator at the
333 end.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000334
335
336.. class:: RawIOBase
337
338 Base class for raw binary I/O. It inherits :class:`IOBase`. There is no
339 public constructor.
340
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000341 Raw binary I/O typically provides low-level access to an underlying OS
342 device or API, and does not try to encapsulate it in high-level primitives
343 (this is left to Buffered I/O and Text I/O, described later in this page).
344
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000345 In addition to the attributes and methods from :class:`IOBase`,
346 RawIOBase provides the following methods:
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000347
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000348 .. method:: read(n=-1)
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000349
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000350 Read up to *n* bytes from the object and return them. As a convenience,
351 if *n* is unspecified or -1, :meth:`readall` is called. Otherwise,
352 only one system call is ever made. Fewer than *n* bytes may be
353 returned if the operating system call returns fewer than *n* bytes.
354
355 If 0 bytes are returned, and *n* was not 0, this indicates end of file.
356 If the object is in non-blocking mode and no bytes are available,
357 ``None`` is returned.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000358
359 .. method:: readall()
360
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000361 Read and return all the bytes from the stream until EOF, using multiple
362 calls to the stream if necessary.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000363
364 .. method:: readinto(b)
365
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000366 Read up to len(b) bytes into bytearray *b* and return the number of bytes
367 read.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000368
369 .. method:: write(b)
370
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000371 Write the given bytes or bytearray object, *b*, to the underlying raw
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000372 stream and return the number of bytes written. This can be less than
373 ``len(b)``, depending on specifics of the underlying raw stream, and
374 especially if it is in non-blocking mode. ``None`` is returned if the
375 raw stream is set not to block and no single byte could be readily
376 written to it.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000377
378
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000379.. class:: BufferedIOBase
380
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000381 Base class for binary streams that support some kind of buffering.
382 It inherits :class:`IOBase`. There is no public constructor.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000383
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000384 The main difference with :class:`RawIOBase` is that methods :meth:`read`,
385 :meth:`readinto` and :meth:`write` will try (respectively) to read as much
386 input as requested or to consume all given output, at the expense of
387 making perhaps more than one system call.
388
389 In addition, those methods can raise :exc:`BlockingIOError` if the
390 underlying raw stream is in non-blocking mode and cannot take or give
391 enough data; unlike their :class:`RawIOBase` counterparts, they will
392 never return ``None``.
393
394 Besides, the :meth:`read` method does not have a default
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000395 implementation that defers to :meth:`readinto`.
396
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000397 A typical :class:`BufferedIOBase` implementation should not inherit from a
398 :class:`RawIOBase` implementation, but wrap one, like
399 :class:`BufferedWriter` and :class:`BufferedReader` do.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000400
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000401 :class:`BufferedIOBase` provides or overrides these members in addition to
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000402 those from :class:`IOBase`:
403
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000404 .. attribute:: raw
405
406 The underlying raw stream (a :class:`RawIOBase` instance) that
407 :class:`BufferedIOBase` deals with. This is not part of the
408 :class:`BufferedIOBase` API and may not exist on some implementations.
409
410 .. method:: detach()
411
412 Separate the underlying raw stream from the buffer and return it.
413
414 After the raw stream has been detached, the buffer is in an unusable
415 state.
416
417 Some buffers, like :class:`BytesIO`, do not have the concept of a single
418 raw stream to return from this method. They raise
419 :exc:`UnsupportedOperation`.
420
421 .. versionadded:: 2.7
422
423 .. method:: read(n=-1)
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000424
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000425 Read and return up to *n* bytes. If the argument is omitted, ``None``, or
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000426 negative, data is read and returned until EOF is reached. An empty bytes
427 object is returned if the stream is already at EOF.
428
429 If the argument is positive, and the underlying raw stream is not
430 interactive, multiple raw reads may be issued to satisfy the byte count
431 (unless EOF is reached first). But for interactive raw streams, at most
432 one raw read will be issued, and a short result does not imply that EOF is
433 imminent.
434
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000435 A :exc:`BlockingIOError` is raised if the underlying raw stream is in
436 non blocking-mode, and has no data available at the moment.
437
438 .. method:: read1(n=-1)
439
440 Read and return up to *n* bytes, with at most one call to the underlying
441 raw stream's :meth:`~RawIOBase.read` method. This can be useful if you
442 are implementing your own buffering on top of a :class:`BufferedIOBase`
443 object.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000444
445 .. method:: readinto(b)
446
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000447 Read up to len(b) bytes into bytearray *b* and return the number of bytes
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000448 read.
449
450 Like :meth:`read`, multiple reads may be issued to the underlying raw
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000451 stream, unless the latter is 'interactive'.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000452
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000453 A :exc:`BlockingIOError` is raised if the underlying raw stream is in
454 non blocking-mode, and has no data available at the moment.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000455
456 .. method:: write(b)
457
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000458 Write the given bytes or bytearray object, *b* and return the number
459 of bytes written (never less than ``len(b)``, since if the write fails
460 an :exc:`IOError` will be raised). Depending on the actual
461 implementation, these bytes may be readily written to the underlying
462 stream, or held in a buffer for performance and latency reasons.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000463
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000464 When in non-blocking mode, a :exc:`BlockingIOError` is raised if the
465 data needed to be written to the raw stream but it couldn't accept
466 all the data without blocking.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000467
468
Benjamin Petersonb6c7beb2009-01-19 16:17:54 +0000469Raw File I/O
470------------
471
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000472.. class:: FileIO(name, mode='r', closefd=True)
Benjamin Petersonb6c7beb2009-01-19 16:17:54 +0000473
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000474 :class:`FileIO` represents an OS-level file containing bytes data.
475 It implements the :class:`RawIOBase` interface (and therefore the
476 :class:`IOBase` interface, too).
477
478 The *name* can be one of two things:
479
480 * a string representing the path to the file which will be opened;
481 * an integer representing the number of an existing OS-level file descriptor
482 to which the resulting :class:`FileIO` object will give access.
Benjamin Petersonb6c7beb2009-01-19 16:17:54 +0000483
484 The *mode* can be ``'r'``, ``'w'`` or ``'a'`` for reading (default), writing,
485 or appending. The file will be created if it doesn't exist when opened for
486 writing or appending; it will be truncated when opened for writing. Add a
487 ``'+'`` to the mode to allow simultaneous reading and writing.
488
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000489 The :meth:`read` (when called with a positive argument), :meth:`readinto`
490 and :meth:`write` methods on this class will only make one system call.
491
Benjamin Petersonb6c7beb2009-01-19 16:17:54 +0000492 In addition to the attributes and methods from :class:`IOBase` and
493 :class:`RawIOBase`, :class:`FileIO` provides the following data
494 attributes and methods:
495
496 .. attribute:: mode
497
498 The mode as given in the constructor.
499
500 .. attribute:: name
501
502 The file name. This is the file descriptor of the file when no name is
503 given in the constructor.
504
Benjamin Petersonb6c7beb2009-01-19 16:17:54 +0000505
506Buffered Streams
507----------------
508
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000509In many situations, buffered I/O streams will provide higher performance
510(bandwidth and latency) than raw I/O streams. Their API is also more usable.
511
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000512.. class:: BytesIO([initial_bytes])
513
514 A stream implementation using an in-memory bytes buffer. It inherits
515 :class:`BufferedIOBase`.
516
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000517 The argument *initial_bytes* is an optional initial :class:`bytes`.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000518
519 :class:`BytesIO` provides or overrides these methods in addition to those
520 from :class:`BufferedIOBase` and :class:`IOBase`:
521
522 .. method:: getvalue()
523
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000524 Return ``bytes`` containing the entire contents of the buffer.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000525
526 .. method:: read1()
527
Benjamin Peterson53be57e2008-04-19 19:34:05 +0000528 In :class:`BytesIO`, this is the same as :meth:`read`.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000529
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000530 .. method:: truncate([size])
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000531
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000532 Truncate the buffer to at most *size* bytes. *size* defaults to the
533 current stream position, as returned by :meth:`tell`.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000534
535
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000536.. class:: BufferedReader(raw, buffer_size=DEFAULT_BUFFER_SIZE)
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000537
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000538 A buffer providing higher-level access to a readable, sequential
539 :class:`RawIOBase` object. It inherits :class:`BufferedIOBase`.
540 When reading data from this object, a larger amount of data may be
541 requested from the underlying raw stream, and kept in an internal buffer.
542 The buffered data can then be returned directly on subsequent reads.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000543
544 The constructor creates a :class:`BufferedReader` for the given readable
545 *raw* stream and *buffer_size*. If *buffer_size* is omitted,
546 :data:`DEFAULT_BUFFER_SIZE` is used.
547
548 :class:`BufferedReader` provides or overrides these methods in addition to
549 those from :class:`BufferedIOBase` and :class:`IOBase`:
550
551 .. method:: peek([n])
552
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000553 Return bytes from the stream without advancing the position. At most one
554 single read on the raw stream is done to satisfy the call. The number of
555 bytes returned may be less or more than requested.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000556
557 .. method:: read([n])
558
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000559 Read and return *n* bytes, or if *n* is not given or negative, until EOF
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000560 or if the read call would block in non-blocking mode.
561
562 .. method:: read1(n)
563
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000564 Read and return up to *n* bytes with only one call on the raw stream. If
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000565 at least one byte is buffered, only buffered bytes are returned.
566 Otherwise, one raw stream read call is made.
567
568
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000569.. class:: BufferedWriter(raw, buffer_size=DEFAULT_BUFFER_SIZE)
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000570
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000571 A buffer providing higher-level access to a writeable, sequential
572 :class:`RawIOBase` object. It inherits :class:`BufferedIOBase`.
573 When writing to this object, data is normally held into an internal
574 buffer. The buffer will be written out to the underlying :class:`RawIOBase`
575 object under various conditions, including:
576
577 * when the buffer gets too small for all pending data;
578 * when :meth:`flush()` is called;
579 * when a :meth:`seek()` is requested (for :class:`BufferedRandom` objects);
580 * when the :class:`BufferedWriter` object is closed or destroyed.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000581
582 The constructor creates a :class:`BufferedWriter` for the given writeable
583 *raw* stream. If the *buffer_size* is not given, it defaults to
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000584 :data:`DEFAULT_BUFFER_SIZE`.
585
586 A third argument, *max_buffer_size*, is supported, but unused and deprecated.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000587
588 :class:`BufferedWriter` provides or overrides these methods in addition to
589 those from :class:`BufferedIOBase` and :class:`IOBase`:
590
591 .. method:: flush()
592
593 Force bytes held in the buffer into the raw stream. A
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000594 :exc:`BlockingIOError` should be raised if the raw stream blocks.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000595
596 .. method:: write(b)
597
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000598 Write the bytes or bytearray object, *b* and return the number of bytes
599 written. When in non-blocking mode, a :exc:`BlockingIOError` is raised
600 if the buffer needs to be written out but the raw stream blocks.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000601
602
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000603.. class:: BufferedRWPair(reader, writer, buffer_size=DEFAULT_BUFFER_SIZE)
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000604
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000605 A buffered I/O object giving a combined, higher-level access to two
606 sequential :class:`RawIOBase` objects: one readable, the other writeable.
607 It is useful for pairs of unidirectional communication channels
608 (pipes, for instance). It inherits :class:`BufferedIOBase`.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000609
610 *reader* and *writer* are :class:`RawIOBase` objects that are readable and
611 writeable respectively. If the *buffer_size* is omitted it defaults to
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000612 :data:`DEFAULT_BUFFER_SIZE`.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000613
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000614 A fourth argument, *max_buffer_size*, is supported, but unused and
615 deprecated.
616
617 :class:`BufferedRWPair` implements all of :class:`BufferedIOBase`\'s methods
618 except for :meth:`~BufferedIOBase.detach`, which raises
619 :exc:`UnsupportedOperation`.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000620
621
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000622.. class:: BufferedRandom(raw, buffer_size=DEFAULT_BUFFER_SIZE)
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000623
624 A buffered interface to random access streams. It inherits
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000625 :class:`BufferedReader` and :class:`BufferedWriter`, and further supports
626 :meth:`seek` and :meth:`tell` functionality.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000627
628 The constructor creates a reader and writer for a seekable raw stream, given
629 in the first argument. If the *buffer_size* is omitted it defaults to
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000630 :data:`DEFAULT_BUFFER_SIZE`.
631
632 A third argument, *max_buffer_size*, is supported, but unused and deprecated.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000633
634 :class:`BufferedRandom` is capable of anything :class:`BufferedReader` or
635 :class:`BufferedWriter` can do.
636
637
638Text I/O
639--------
640
641.. class:: TextIOBase
642
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000643 Base class for text streams. This class provides an unicode character
644 and line based interface to stream I/O. There is no :meth:`readinto`
645 method because Python's :class:`unicode` strings are immutable.
646 It inherits :class:`IOBase`. There is no public constructor.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000647
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000648 :class:`TextIOBase` provides or overrides these data attributes and
649 methods in addition to those from :class:`IOBase`:
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000650
651 .. attribute:: encoding
652
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000653 The name of the encoding used to decode the stream's bytes into
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000654 strings, and to encode strings into bytes.
655
Antoine Pitrou19690592009-06-12 20:14:08 +0000656 .. attribute:: errors
657
658 The error setting of the decoder or encoder.
659
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000660 .. attribute:: newlines
661
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000662 A string, a tuple of strings, or ``None``, indicating the newlines
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000663 translated so far. Depending on the implementation and the initial
664 constructor flags, this may not be available.
665
666 .. attribute:: buffer
667
668 The underlying binary buffer (a :class:`BufferedIOBase` instance) that
669 :class:`TextIOBase` deals with. This is not part of the
670 :class:`TextIOBase` API and may not exist on some implementations.
671
672 .. method:: detach()
673
674 Separate the underlying binary buffer from the :class:`TextIOBase` and
675 return it.
676
677 After the underlying buffer has been detached, the :class:`TextIOBase` is
678 in an unusable state.
679
680 Some :class:`TextIOBase` implementations, like :class:`StringIO`, may not
681 have the concept of an underlying buffer and calling this method will
682 raise :exc:`UnsupportedOperation`.
683
684 .. versionadded:: 2.7
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000685
686 .. method:: read(n)
687
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000688 Read and return at most *n* characters from the stream as a single
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000689 :class:`unicode`. If *n* is negative or ``None``, reads until EOF.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000690
691 .. method:: readline()
692
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000693 Read until newline or EOF and return a single ``unicode``. If the
694 stream is already at EOF, an empty string is returned.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000695
696 .. method:: write(s)
697
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000698 Write the :class:`unicode` string *s* to the stream and return the
699 number of characters written.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000700
701
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000702.. class:: TextIOWrapper(buffer, encoding=None, errors=None, newline=None, line_buffering=False)
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000703
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000704 A buffered text stream over a :class:`BufferedIOBase` binary stream.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000705 It inherits :class:`TextIOBase`.
706
707 *encoding* gives the name of the encoding that the stream will be decoded or
708 encoded with. It defaults to :func:`locale.getpreferredencoding`.
709
Benjamin Peterson53be57e2008-04-19 19:34:05 +0000710 *errors* is an optional string that specifies how encoding and decoding
711 errors are to be handled. Pass ``'strict'`` to raise a :exc:`ValueError`
712 exception if there is an encoding error (the default of ``None`` has the same
713 effect), or pass ``'ignore'`` to ignore errors. (Note that ignoring encoding
714 errors can lead to data loss.) ``'replace'`` causes a replacement marker
Benjamin Petersona7d09032008-04-19 19:47:34 +0000715 (such as ``'?'``) to be inserted where there is malformed data. When
716 writing, ``'xmlcharrefreplace'`` (replace with the appropriate XML character
717 reference) or ``'backslashreplace'`` (replace with backslashed escape
718 sequences) can be used. Any other error handling name that has been
719 registered with :func:`codecs.register_error` is also valid.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000720
721 *newline* can be ``None``, ``''``, ``'\n'``, ``'\r'``, or ``'\r\n'``. It
722 controls the handling of line endings. If it is ``None``, universal newlines
723 is enabled. With this enabled, on input, the lines endings ``'\n'``,
724 ``'\r'``, or ``'\r\n'`` are translated to ``'\n'`` before being returned to
725 the caller. Conversely, on output, ``'\n'`` is translated to the system
Mark Dickinson3e4caeb2009-02-21 20:27:01 +0000726 default line separator, :data:`os.linesep`. If *newline* is any other of its
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000727 legal values, that newline becomes the newline when the file is read and it
728 is returned untranslated. On output, ``'\n'`` is converted to the *newline*.
729
730 If *line_buffering* is ``True``, :meth:`flush` is implied when a call to
731 write contains a newline character.
732
Antoine Pitrou19690592009-06-12 20:14:08 +0000733 :class:`TextIOWrapper` provides one attribute in addition to those of
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000734 :class:`TextIOBase` and its parents:
735
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000736 .. attribute:: line_buffering
737
738 Whether line buffering is enabled.
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000739
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000740
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000741.. class:: StringIO(initial_value=u'', newline=None)
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000742
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000743 An in-memory stream for unicode text. It inherits :class:`TextIOWrapper`.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000744
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000745 The initial value of the buffer (an empty unicode string by default) can
746 be set by providing *initial_value*. The *newline* argument works like
747 that of :class:`TextIOWrapper`. The default is to do no newline
748 translation.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000749
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000750 :class:`StringIO` provides this method in addition to those from
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000751 :class:`TextIOWrapper` and its parents:
752
753 .. method:: getvalue()
754
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000755 Return a ``unicode`` containing the entire contents of the buffer at any
756 time before the :class:`StringIO` object's :meth:`close` method is
757 called.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000758
Antoine Pitrouc9062ca2009-10-01 17:08:03 +0000759 Example usage::
760
761 import io
762
763 output = io.StringIO()
764 output.write(u'First line.\n')
765 output.write(u'Second line.\n')
766
767 # Retrieve file contents -- this will be
768 # u'First line.\nSecond line.\n'
769 contents = output.getvalue()
770
771 # Close object and discard memory buffer --
772 # .getvalue() will now raise an exception.
773 output.close()
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000774
775.. class:: IncrementalNewlineDecoder
776
777 A helper codec that decodes newlines for universal newlines mode. It
778 inherits :class:`codecs.IncrementalDecoder`.
779