~ubuntu-branches/ubuntu/maverick/python3.1/maverick

« back to all changes in this revision

Viewing changes to Doc/library/io.rst

  • Committer: Bazaar Package Importer
  • Author(s): Matthias Klose
  • Date: 2009-03-23 00:01:27 UTC
  • Revision ID: james.westby@ubuntu.com-20090323000127-5fstfxju4ufrhthq
Tags: upstream-3.1~a1+20090322
ImportĀ upstreamĀ versionĀ 3.1~a1+20090322

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
: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>
 
9
.. moduleauthor:: Antoine Pitrou <solipsis@pitrou.net>
 
10
.. moduleauthor:: Amaury Forgeot d'Arc <amauryfa@gmail.com>
 
11
.. sectionauthor:: Benjamin Peterson <benjamin@python.org>
 
12
 
 
13
The :mod:`io` module provides the Python interfaces to stream handling.  The
 
14
builtin :func:`open` function is defined in this module.
 
15
 
 
16
At the top of the I/O hierarchy is the abstract base class :class:`IOBase`.  It
 
17
defines the basic interface to a stream.  Note, however, that there is no
 
18
separation between reading and writing to streams; implementations are allowed
 
19
to throw an :exc:`IOError` if they do not support a given operation.
 
20
 
 
21
Extending :class:`IOBase` is :class:`RawIOBase` which deals simply with the
 
22
reading and writing of raw bytes to a stream.  :class:`FileIO` subclasses
 
23
:class:`RawIOBase` to provide an interface to files in the machine's
 
24
file system.
 
25
 
 
26
:class:`BufferedIOBase` deals with buffering on a raw byte stream
 
27
(:class:`RawIOBase`).  Its subclasses, :class:`BufferedWriter`,
 
28
:class:`BufferedReader`, and :class:`BufferedRWPair` buffer streams that are
 
29
readable, writable, and both readable and writable.
 
30
:class:`BufferedRandom` provides a buffered interface to random access
 
31
streams.  :class:`BytesIO` is a simple stream of in-memory bytes.
 
32
 
 
33
Another :class:`IOBase` subclass, :class:`TextIOBase`, deals with
 
34
streams whose bytes represent text, and handles encoding and decoding
 
35
from and to strings. :class:`TextIOWrapper`, which extends it, is a
 
36
buffered text interface to a buffered raw stream
 
37
(:class:`BufferedIOBase`). Finally, :class:`StringIO` is an in-memory
 
38
stream for text.
 
39
 
 
40
Argument names are not part of the specification, and only the arguments of
 
41
:func:`open` are intended to be used as keyword arguments.
 
42
 
 
43
 
 
44
Module Interface
 
45
----------------
 
46
 
 
47
.. data:: DEFAULT_BUFFER_SIZE
 
48
 
 
49
   An int containing the default buffer size used by the module's buffered I/O
 
50
   classes.  :func:`open` uses the file's blksize (as obtained by
 
51
   :func:`os.stat`) if possible.
 
52
 
 
53
.. function:: open(file[, mode[, buffering[, encoding[, errors[, newline[, closefd=True]]]]]])
 
54
 
 
55
   Open *file* and return a stream.  If the file cannot be opened, an
 
56
   :exc:`IOError` is raised.
 
57
 
 
58
   *file* is either a string giving the name (and the path if the file isn't in
 
59
   the current working directory) of the file to be opened or a file
 
60
   descriptor of the file to be opened.  (If a file descriptor is given,
 
61
   for example, from :func:`os.fdopen`, it is closed when the returned
 
62
   I/O object is closed, unless *closefd* is set to ``False``.)
 
63
 
 
64
   *mode* is an optional string that specifies the mode in which the file is
 
65
   opened.  It defaults to ``'r'`` which means open for reading in text mode.
 
66
   Other common values are ``'w'`` for writing (truncating the file if it
 
67
   already exists), and ``'a'`` for appending (which on *some* Unix systems,
 
68
   means that *all* writes append to the end of the file regardless of the
 
69
   current seek position).  In text mode, if *encoding* is not specified the
 
70
   encoding used is platform dependent. (For reading and writing raw bytes use
 
71
   binary mode and leave *encoding* unspecified.)  The available modes are:
 
72
 
 
73
   ========= ===============================================================
 
74
   Character Meaning
 
75
   --------- ---------------------------------------------------------------
 
76
   ``'r'``   open for reading (default)
 
77
   ``'w'``   open for writing, truncating the file first
 
78
   ``'a'``   open for writing, appending to the end of the file if it exists
 
79
   ``'b'``   binary mode
 
80
   ``'t'``   text mode (default)
 
81
   ``'+'``   open a disk file for updating (reading and writing)
 
82
   ``'U'``   universal newline mode (for backwards compatibility; should
 
83
             not be used in new code)
 
84
   ========= ===============================================================
 
85
 
 
86
   The default mode is ``'rt'`` (open for reading text).  For binary random
 
87
   access, the mode ``'w+b'`` opens and truncates the file to 0 bytes, while
 
88
   ``'r+b'`` opens the file without truncation.
 
89
 
 
90
   Python distinguishes between files opened in binary and text modes, even when
 
91
   the underlying operating system doesn't.  Files opened in binary mode
 
92
   (including ``'b'`` in the *mode* argument) return contents as ``bytes``
 
93
   objects without any decoding.  In text mode (the default, or when ``'t'`` is
 
94
   included in the *mode* argument), the contents of the file are returned as
 
95
   strings, the bytes having been first decoded using a platform-dependent
 
96
   encoding or using the specified *encoding* if given.
 
97
 
 
98
   *buffering* is an optional integer used to set the buffering policy.  By
 
99
   default full buffering is on.  Pass 0 to switch buffering off (only allowed
 
100
   in binary mode), 1 to set line buffering, and an integer > 1 for full
 
101
   buffering.
 
102
 
 
103
   *encoding* is the name of the encoding used to decode or encode the file.
 
104
   This should only be used in text mode.  The default encoding is platform
 
105
   dependent, but any encoding supported by Python can be used.  See the
 
106
   :mod:`codecs` module for the list of supported encodings.
 
107
 
 
108
   *errors* is an optional string that specifies how encoding and decoding
 
109
   errors are to be handled.  Pass ``'strict'`` to raise a :exc:`ValueError`
 
110
   exception if there is an encoding error (the default of ``None`` has the same
 
111
   effect), or pass ``'ignore'`` to ignore errors.  (Note that ignoring encoding
 
112
   errors can lead to data loss.)  ``'replace'`` causes a replacement marker
 
113
   (such as ``'?'``) to be inserted where there is malformed data.  When
 
114
   writing, ``'xmlcharrefreplace'`` (replace with the appropriate XML character
 
115
   reference) or ``'backslashreplace'`` (replace with backslashed escape
 
116
   sequences) can be used.  Any other error handling name that has been
 
117
   registered with :func:`codecs.register_error` is also valid.
 
118
 
 
119
   *newline* controls how universal newlines works (it only applies to text
 
120
   mode).  It can be ``None``, ``''``, ``'\n'``, ``'\r'``, and ``'\r\n'``.  It
 
121
   works as follows:
 
122
 
 
123
   * On input, if *newline* is ``None``, universal newlines mode is enabled.
 
124
     Lines in the input can end in ``'\n'``, ``'\r'``, or ``'\r\n'``, and these
 
125
     are translated into ``'\n'`` before being returned to the caller.  If it is
 
126
     ``''``, universal newline mode is enabled, but line endings are returned to
 
127
     the caller untranslated.  If it has any of the other legal values, input
 
128
     lines are only terminated by the given string, and the line ending is
 
129
     returned to the caller untranslated.
 
130
 
 
131
   * On output, if *newline* is ``None``, any ``'\n'`` characters written are
 
132
     translated to the system default line separator, :data:`os.linesep`.  If
 
133
     *newline* is ``''``, no translation takes place.  If *newline* is any of
 
134
     the other legal values, any ``'\n'`` characters written are translated to
 
135
     the given string.
 
136
 
 
137
   If *closefd* is ``False`` and a file descriptor rather than a
 
138
   filename was given, the underlying file descriptor will be kept open
 
139
   when the file is closed.  If a filename is given *closefd* has no
 
140
   effect but must be ``True`` (the default).
 
141
 
 
142
   The type of file object returned by the :func:`open` function depends
 
143
   on the mode.  When :func:`open` is used to open a file in a text mode
 
144
   (``'w'``, ``'r'``, ``'wt'``, ``'rt'``, etc.), it returns a
 
145
   :class:`TextIOWrapper`. When used to open a file in a binary mode,
 
146
   the returned class varies: in read binary mode, it returns a
 
147
   :class:`BufferedReader`; in write binary and append binary modes, it
 
148
   returns a :class:`BufferedWriter`, and in read/write mode, it returns
 
149
   a :class:`BufferedRandom`.
 
150
 
 
151
   It is also possible to use a string or bytearray as a file for both reading
 
152
   and writing.  For strings :class:`StringIO` can be used like a file opened in
 
153
   a text mode, and for bytearrays a :class:`BytesIO` can be used like a
 
154
   file opened in a binary mode.
 
155
 
 
156
 
 
157
.. exception:: BlockingIOError
 
158
 
 
159
   Error raised when blocking would occur on a non-blocking stream.  It inherits
 
160
   :exc:`IOError`.
 
161
 
 
162
   In addition to those of :exc:`IOError`, :exc:`BlockingIOError` has one
 
163
   attribute:
 
164
 
 
165
   .. attribute:: characters_written
 
166
 
 
167
      An integer containing the number of characters written to the stream
 
168
      before it blocked.
 
169
 
 
170
 
 
171
.. exception:: UnsupportedOperation
 
172
 
 
173
   An exception inheriting :exc:`IOError` and :exc:`ValueError` that is raised
 
174
   when an unsupported operation is called on a stream.
 
175
 
 
176
 
 
177
I/O Base Classes
 
178
----------------
 
179
 
 
180
.. class:: IOBase
 
181
 
 
182
   The abstract base class for all I/O classes, acting on streams of bytes.
 
183
   There is no public constructor.
 
184
 
 
185
   This class provides empty abstract implementations for many methods
 
186
   that derived classes can override selectively; the default
 
187
   implementations represent a file that cannot be read, written or
 
188
   seeked.
 
189
 
 
190
   Even though :class:`IOBase` does not declare :meth:`read`, :meth:`readinto`,
 
191
   or :meth:`write` because their signatures will vary, implementations and
 
192
   clients should consider those methods part of the interface.  Also,
 
193
   implementations may raise a :exc:`IOError` when operations they do not
 
194
   support are called.
 
195
 
 
196
   The basic type used for binary data read from or written to a file is
 
197
   :class:`bytes`.  :class:`bytearray`\s are accepted too, and in some cases
 
198
   (such as :class:`readinto`) required.  Text I/O classes work with
 
199
   :class:`str` data.
 
200
 
 
201
   Note that calling any method (even inquiries) on a closed stream is
 
202
   undefined.  Implementations may raise :exc:`IOError` in this case.
 
203
 
 
204
   IOBase (and its subclasses) support the iterator protocol, meaning that an
 
205
   :class:`IOBase` object can be iterated over yielding the lines in a stream.
 
206
 
 
207
   IOBase is also a context manager and therefore supports the
 
208
   :keyword:`with` statement.  In this example, *file* is closed after the
 
209
   :keyword:`with` statement's suite is finished---even if an exception occurs::
 
210
 
 
211
      with open('spam.txt', 'w') as file:
 
212
          file.write('Spam and eggs!')
 
213
 
 
214
   :class:`IOBase` provides these data attributes and methods:
 
215
 
 
216
   .. method:: close()
 
217
 
 
218
      Flush and close this stream. This method has no effect if the file is
 
219
      already closed. Once the file is closed, any operation on the file
 
220
      (e.g. reading or writing) will raise an :exc:`IOError`. The internal
 
221
      file descriptor isn't closed if *closefd* was False.
 
222
 
 
223
   .. attribute:: closed
 
224
 
 
225
      True if the stream is closed.
 
226
 
 
227
   .. method:: fileno()
 
228
 
 
229
      Return the underlying file descriptor (an integer) of the stream if it
 
230
      exists.  An :exc:`IOError` is raised if the IO object does not use a file
 
231
      descriptor.
 
232
 
 
233
   .. method:: flush()
 
234
 
 
235
      Flush the write buffers of the stream if applicable.  This does nothing
 
236
      for read-only and non-blocking streams.
 
237
 
 
238
   .. method:: isatty()
 
239
 
 
240
      Return ``True`` if the stream is interactive (i.e., connected to
 
241
      a terminal/tty device).
 
242
 
 
243
   .. method:: readable()
 
244
 
 
245
      Return ``True`` if the stream can be read from.  If False, :meth:`read`
 
246
      will raise :exc:`IOError`.
 
247
 
 
248
   .. method:: readline([limit])
 
249
 
 
250
      Read and return one line from the stream.  If *limit* is specified, at
 
251
      most *limit* bytes will be read.
 
252
 
 
253
      The line terminator is always ``b'\n'`` for binary files; for text files,
 
254
      the *newlines* argument to :func:`open` can be used to select the line
 
255
      terminator(s) recognized.
 
256
 
 
257
   .. method:: readlines([hint])
 
258
 
 
259
      Read and return a list of lines from the stream.  *hint* can be specified
 
260
      to control the number of lines read: no more lines will be read if the
 
261
      total size (in bytes/characters) of all lines so far exceeds *hint*.
 
262
 
 
263
   .. method:: seek(offset[, whence])
 
264
 
 
265
      Change the stream position to the given byte *offset*.  *offset* is
 
266
      interpreted relative to the position indicated by *whence*.  Values for
 
267
      *whence* are:
 
268
 
 
269
      * ``0`` -- start of the stream (the default); *offset* should be zero or positive
 
270
      * ``1`` -- current stream position; *offset* may be negative
 
271
      * ``2`` -- end of the stream; *offset* is usually negative
 
272
 
 
273
      Return the new absolute position.
 
274
 
 
275
   .. method:: seekable()
 
276
 
 
277
      Return ``True`` if the stream supports random access.  If ``False``,
 
278
      :meth:`seek`, :meth:`tell` and :meth:`truncate` will raise :exc:`IOError`.
 
279
 
 
280
   .. method:: tell()
 
281
 
 
282
      Return the current stream position.
 
283
 
 
284
   .. method:: truncate([size])
 
285
 
 
286
      Truncate the file to at most *size* bytes.  *size* defaults to the current
 
287
      file position, as returned by :meth:`tell`.
 
288
 
 
289
   .. method:: writable()
 
290
 
 
291
      Return ``True`` if the stream supports writing.  If ``False``,
 
292
      :meth:`write` and :meth:`truncate` will raise :exc:`IOError`.
 
293
 
 
294
   .. method:: writelines(lines)
 
295
 
 
296
      Write a list of lines to the stream.  Line separators are not added, so it
 
297
      is usual for each of the lines provided to have a line separator at the
 
298
      end.
 
299
 
 
300
 
 
301
.. class:: RawIOBase
 
302
 
 
303
   Base class for raw binary I/O.  It inherits :class:`IOBase`.  There is no
 
304
   public constructor.
 
305
 
 
306
   In addition to the attributes and methods from :class:`IOBase`,
 
307
   RawIOBase provides the following methods:
 
308
 
 
309
   .. method:: read([n])
 
310
 
 
311
      Read and return all the bytes from the stream until EOF, or if *n* is
 
312
      specified, up to *n* bytes.  Only one system call is ever made.  An empty
 
313
      bytes object is returned on EOF; ``None`` is returned if the object is set
 
314
      not to block and has no data to read.
 
315
 
 
316
   .. method:: readall()
 
317
 
 
318
      Read and return all the bytes from the stream until EOF, using multiple
 
319
      calls to the stream if necessary.
 
320
 
 
321
   .. method:: readinto(b)
 
322
 
 
323
      Read up to len(b) bytes into bytearray *b* and return the number of bytes
 
324
      read.
 
325
 
 
326
   .. method:: write(b)
 
327
 
 
328
      Write the given bytes or bytearray object, *b*, to the underlying raw
 
329
      stream and return the number of bytes written (This is never less than
 
330
      ``len(b)``, since if the write fails, an :exc:`IOError` will be raised).
 
331
 
 
332
 
 
333
.. class:: BufferedIOBase
 
334
 
 
335
   Base class for streams that support buffering.  It inherits :class:`IOBase`.
 
336
   There is no public constructor.
 
337
 
 
338
   The main difference with :class:`RawIOBase` is that the :meth:`read` method
 
339
   supports omitting the *size* argument, and does not have a default
 
340
   implementation that defers to :meth:`readinto`.
 
341
 
 
342
   In addition, :meth:`read`, :meth:`readinto`, and :meth:`write` may raise
 
343
   :exc:`BlockingIOError` if the underlying raw stream is in non-blocking mode
 
344
   and not ready; unlike their raw counterparts, they will never return
 
345
   ``None``.
 
346
 
 
347
   A typical implementation should not inherit from a :class:`RawIOBase`
 
348
   implementation, but wrap one like :class:`BufferedWriter` and
 
349
   :class:`BufferedReader`.
 
350
 
 
351
   :class:`BufferedIOBase` provides or overrides these methods in addition to
 
352
   those from :class:`IOBase`:
 
353
 
 
354
   .. method:: read([n])
 
355
 
 
356
      Read and return up to *n* bytes.  If the argument is omitted, ``None``, or
 
357
      negative, data is read and returned until EOF is reached.  An empty bytes
 
358
      object is returned if the stream is already at EOF.
 
359
 
 
360
      If the argument is positive, and the underlying raw stream is not
 
361
      interactive, multiple raw reads may be issued to satisfy the byte count
 
362
      (unless EOF is reached first).  But for interactive raw streams, at most
 
363
      one raw read will be issued, and a short result does not imply that EOF is
 
364
      imminent.
 
365
 
 
366
      A :exc:`BlockingIOError` is raised if the underlying raw stream has no
 
367
      data at the moment.
 
368
 
 
369
   .. method:: read1([n])
 
370
 
 
371
      Read and return up to *n* bytes, with at most one call to the underlying
 
372
      raw stream's :meth:`~RawIOBase.read` method.
 
373
 
 
374
   .. method:: readinto(b)
 
375
 
 
376
      Read up to len(b) bytes into bytearray *b* and return the number of bytes
 
377
      read.
 
378
 
 
379
      Like :meth:`read`, multiple reads may be issued to the underlying raw
 
380
      stream, unless the latter is 'interactive.'
 
381
 
 
382
      A :exc:`BlockingIOError` is raised if the underlying raw stream has no
 
383
      data at the moment.
 
384
 
 
385
   .. method:: write(b)
 
386
 
 
387
      Write the given bytes or bytearray object, *b*, to the underlying raw
 
388
      stream and return the number of bytes written (never less than ``len(b)``,
 
389
      since if the write fails an :exc:`IOError` will be raised).
 
390
 
 
391
      A :exc:`BlockingIOError` is raised if the buffer is full, and the
 
392
      underlying raw stream cannot accept more data at the moment.
 
393
 
 
394
 
 
395
Raw File I/O
 
396
------------
 
397
 
 
398
.. class:: FileIO(name[, mode])
 
399
 
 
400
   :class:`FileIO` represents a file containing bytes data.  It implements
 
401
   the :class:`RawIOBase` interface (and therefore the :class:`IOBase`
 
402
   interface, too).
 
403
 
 
404
   The *mode* can be ``'r'``, ``'w'`` or ``'a'`` for reading (default), writing,
 
405
   or appending.  The file will be created if it doesn't exist when opened for
 
406
   writing or appending; it will be truncated when opened for writing.  Add a
 
407
   ``'+'`` to the mode to allow simultaneous reading and writing.
 
408
 
 
409
   In addition to the attributes and methods from :class:`IOBase` and
 
410
   :class:`RawIOBase`, :class:`FileIO` provides the following data
 
411
   attributes and methods:
 
412
 
 
413
   .. attribute:: mode
 
414
 
 
415
      The mode as given in the constructor.
 
416
 
 
417
   .. attribute:: name
 
418
 
 
419
      The file name.  This is the file descriptor of the file when no name is
 
420
      given in the constructor.
 
421
 
 
422
   .. method:: read([n])
 
423
 
 
424
      Read and return at most *n* bytes.  Only one system call is made, so it is
 
425
      possible that less data than was requested is returned.  Use :func:`len`
 
426
      on the returned bytes object to see how many bytes were actually returned.
 
427
      (In non-blocking mode, ``None`` is returned when no data is available.)
 
428
 
 
429
   .. method:: readall()
 
430
 
 
431
      Read and return the entire file's contents in a single bytes object.  As
 
432
      much as immediately available is returned in non-blocking mode.  If the
 
433
      EOF has been reached, ``b''`` is returned.
 
434
 
 
435
   .. method:: write(b)
 
436
 
 
437
      Write the bytes or bytearray object, *b*, to the file, and return
 
438
      the number actually written. Only one system call is made, so it
 
439
      is possible that only some of the data is written.
 
440
 
 
441
 
 
442
Buffered Streams
 
443
----------------
 
444
 
 
445
.. class:: BytesIO([initial_bytes])
 
446
 
 
447
   A stream implementation using an in-memory bytes buffer.  It inherits
 
448
   :class:`BufferedIOBase`.
 
449
 
 
450
   The argument *initial_bytes* is an optional initial bytearray.
 
451
 
 
452
   :class:`BytesIO` provides or overrides these methods in addition to those
 
453
   from :class:`BufferedIOBase` and :class:`IOBase`:
 
454
 
 
455
   .. method:: getvalue()
 
456
 
 
457
      Return ``bytes`` containing the entire contents of the buffer.
 
458
 
 
459
   .. method:: read1()
 
460
 
 
461
      In :class:`BytesIO`, this is the same as :meth:`read`.
 
462
 
 
463
   .. method:: truncate([size])
 
464
 
 
465
      Truncate the buffer to at most *size* bytes.  *size* defaults to the
 
466
      current stream position, as returned by :meth:`tell`.
 
467
 
 
468
 
 
469
.. class:: BufferedReader(raw[, buffer_size])
 
470
 
 
471
   A buffer for a readable, sequential :class:`RawIOBase` object.  It inherits
 
472
   :class:`BufferedIOBase`.
 
473
 
 
474
   The constructor creates a :class:`BufferedReader` for the given readable
 
475
   *raw* stream and *buffer_size*.  If *buffer_size* is omitted,
 
476
   :data:`DEFAULT_BUFFER_SIZE` is used.
 
477
 
 
478
   :class:`BufferedReader` provides or overrides these methods in addition to
 
479
   those from :class:`BufferedIOBase` and :class:`IOBase`:
 
480
 
 
481
   .. method:: peek([n])
 
482
 
 
483
      Return 1 (or *n* if specified) bytes from a buffer without advancing the
 
484
      position.  Only a single read on the raw stream is done to satisfy the
 
485
      call. The number of bytes returned may be less than requested since at
 
486
      most all the buffer's bytes from the current position to the end are
 
487
      returned.
 
488
 
 
489
   .. method:: read([n])
 
490
 
 
491
      Read and return *n* bytes, or if *n* is not given or negative, until EOF
 
492
      or if the read call would block in non-blocking mode.
 
493
 
 
494
   .. method:: read1(n)
 
495
 
 
496
      Read and return up to *n* bytes with only one call on the raw stream.  If
 
497
      at least one byte is buffered, only buffered bytes are returned.
 
498
      Otherwise, one raw stream read call is made.
 
499
 
 
500
 
 
501
.. class:: BufferedWriter(raw[, buffer_size[, max_buffer_size]])
 
502
 
 
503
   A buffer for a writeable sequential RawIO object.  It inherits
 
504
   :class:`BufferedIOBase`.
 
505
 
 
506
   The constructor creates a :class:`BufferedWriter` for the given writeable
 
507
   *raw* stream.  If the *buffer_size* is not given, it defaults to
 
508
   :data:`DEFAULT_BUFFER_SIZE`.
 
509
 
 
510
   *max_buffer_size* is unused and deprecated.
 
511
 
 
512
   :class:`BufferedWriter` provides or overrides these methods in addition to
 
513
   those from :class:`BufferedIOBase` and :class:`IOBase`:
 
514
 
 
515
   .. method:: flush()
 
516
 
 
517
      Force bytes held in the buffer into the raw stream.  A
 
518
      :exc:`BlockingIOError` should be raised if the raw stream blocks.
 
519
 
 
520
   .. method:: write(b)
 
521
 
 
522
      Write the bytes or bytearray object, *b*, onto the raw stream and return
 
523
      the number of bytes written.  A :exc:`BlockingIOError` is raised when the
 
524
      raw stream blocks.
 
525
 
 
526
 
 
527
.. class:: BufferedRWPair(reader, writer[, buffer_size[, max_buffer_size]])
 
528
 
 
529
   A combined buffered writer and reader object for a raw stream that can be
 
530
   written to and read from.  It has and supports both :meth:`read`, :meth:`write`,
 
531
   and their variants.  This is useful for sockets and two-way pipes.
 
532
   It inherits :class:`BufferedIOBase`.
 
533
 
 
534
   *reader* and *writer* are :class:`RawIOBase` objects that are readable and
 
535
   writeable respectively.  If the *buffer_size* is omitted it defaults to
 
536
   :data:`DEFAULT_BUFFER_SIZE`.
 
537
 
 
538
   *max_buffer_size* is unused and deprecated.
 
539
 
 
540
   :class:`BufferedRWPair` implements all of :class:`BufferedIOBase`\'s methods.
 
541
 
 
542
 
 
543
.. class:: BufferedRandom(raw[, buffer_size[, max_buffer_size]])
 
544
 
 
545
   A buffered interface to random access streams.  It inherits
 
546
   :class:`BufferedReader` and :class:`BufferedWriter`.
 
547
 
 
548
   The constructor creates a reader and writer for a seekable raw stream, given
 
549
   in the first argument.  If the *buffer_size* is omitted it defaults to
 
550
   :data:`DEFAULT_BUFFER_SIZE`.
 
551
 
 
552
   *max_buffer_size* is unused and deprecated.
 
553
 
 
554
   :class:`BufferedRandom` is capable of anything :class:`BufferedReader` or
 
555
   :class:`BufferedWriter` can do.
 
556
 
 
557
 
 
558
Text I/O
 
559
--------
 
560
 
 
561
.. class:: TextIOBase
 
562
 
 
563
   Base class for text streams.  This class provides a character and line based
 
564
   interface to stream I/O.  There is no :meth:`readinto` method because
 
565
   Python's character strings are immutable.  It inherits :class:`IOBase`.
 
566
   There is no public constructor.
 
567
 
 
568
   :class:`TextIOBase` provides or overrides these data attributes and
 
569
   methods in addition to those from :class:`IOBase`:
 
570
 
 
571
   .. attribute:: encoding
 
572
 
 
573
      The name of the encoding used to decode the stream's bytes into
 
574
      strings, and to encode strings into bytes.
 
575
 
 
576
   .. attribute:: newlines
 
577
 
 
578
      A string, a tuple of strings, or ``None``, indicating the newlines
 
579
      translated so far.
 
580
 
 
581
   .. method:: read(n)
 
582
 
 
583
      Read and return at most *n* characters from the stream as a single
 
584
      :class:`str`.  If *n* is negative or ``None``, reads to EOF.
 
585
 
 
586
   .. method:: readline()
 
587
 
 
588
      Read until newline or EOF and return a single ``str``.  If the stream is
 
589
      already at EOF, an empty string is returned.
 
590
 
 
591
   .. method:: write(s)
 
592
 
 
593
      Write the string *s* to the stream and return the number of characters
 
594
      written.
 
595
 
 
596
 
 
597
.. class:: TextIOWrapper(buffer[, encoding[, errors[, newline[, line_buffering]]]])
 
598
 
 
599
   A buffered text stream over a :class:`BufferedIOBase` raw stream, *buffer*.
 
600
   It inherits :class:`TextIOBase`.
 
601
 
 
602
   *encoding* gives the name of the encoding that the stream will be decoded or
 
603
   encoded with.  It defaults to :func:`locale.getpreferredencoding`.
 
604
 
 
605
   *errors* is an optional string that specifies how encoding and decoding
 
606
   errors are to be handled.  Pass ``'strict'`` to raise a :exc:`ValueError`
 
607
   exception if there is an encoding error (the default of ``None`` has the same
 
608
   effect), or pass ``'ignore'`` to ignore errors.  (Note that ignoring encoding
 
609
   errors can lead to data loss.)  ``'replace'`` causes a replacement marker
 
610
   (such as ``'?'``) to be inserted where there is malformed data.  When
 
611
   writing, ``'xmlcharrefreplace'`` (replace with the appropriate XML character
 
612
   reference) or ``'backslashreplace'`` (replace with backslashed escape
 
613
   sequences) can be used.  Any other error handling name that has been
 
614
   registered with :func:`codecs.register_error` is also valid.
 
615
 
 
616
   *newline* can be ``None``, ``''``, ``'\n'``, ``'\r'``, or ``'\r\n'``.  It
 
617
   controls the handling of line endings.  If it is ``None``, universal newlines
 
618
   is enabled.  With this enabled, on input, the lines endings ``'\n'``,
 
619
   ``'\r'``, or ``'\r\n'`` are translated to ``'\n'`` before being returned to
 
620
   the caller.  Conversely, on output, ``'\n'`` is translated to the system
 
621
   default line separator, :data:`os.linesep`.  If *newline* is any other of its
 
622
   legal values, that newline becomes the newline when the file is read and it
 
623
   is returned untranslated.  On output, ``'\n'`` is converted to the *newline*.
 
624
 
 
625
   If *line_buffering* is ``True``, :meth:`flush` is implied when a call to
 
626
   write contains a newline character.
 
627
 
 
628
   :class:`TextIOWrapper` provides these data attributes in addition to those of
 
629
   :class:`TextIOBase` and its parents:
 
630
 
 
631
   .. attribute:: errors
 
632
 
 
633
      The encoding and decoding error setting.
 
634
 
 
635
   .. attribute:: line_buffering
 
636
 
 
637
      Whether line buffering is enabled.
 
638
 
 
639
 
 
640
.. class:: StringIO([initial_value[, newline]])
 
641
 
 
642
   An in-memory stream for text.  It inherits :class:`TextIOWrapper`.
 
643
 
 
644
   The initial value of the buffer (an empty string by default) can be set by
 
645
   providing *initial_value*.  The *newline* argument works like that of
 
646
   :class:`TextIOWrapper`.  The default is to do no newline translation.
 
647
 
 
648
   :class:`StringIO` provides this method in addition to those from
 
649
   :class:`TextIOWrapper` and its parents:
 
650
 
 
651
   .. method:: getvalue()
 
652
 
 
653
      Return a ``str`` containing the entire contents of the buffer at any
 
654
      time before the :class:`StringIO` object's :meth:`close` method is
 
655
      called.
 
656
 
 
657
   Example usage::
 
658
 
 
659
      import io
 
660
 
 
661
      output = io.StringIO()
 
662
      output.write('First line.\n')
 
663
      print('Second line.', file=output)
 
664
 
 
665
      # Retrieve file contents -- this will be
 
666
      # 'First line.\nSecond line.\n'
 
667
      contents = output.getvalue()
 
668
 
 
669
      # Close object and discard memory buffer --
 
670
      # .getvalue() will now raise an exception.
 
671
      output.close()
 
672
 
 
673
.. class:: IncrementalNewlineDecoder
 
674
 
 
675
   A helper codec that decodes newlines for universal newlines mode.  It
 
676
   inherits :class:`codecs.IncrementalDecoder`.
 
677