blob: 6280adc14e3a8dea94abbf9b46faad8f1dda1e45 [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>
9.. sectionauthor:: Benjamin Peterson
10
11The :mod:`io` module provides the Python interfaces to stream handling. The
12builtin :func:`open` function is defined in this module.
13
14At the top of the I/O hierarchy is the abstract base class :class:`IOBase`. It
15defines the basic interface to a stream. Note, however, that there is no
16seperation between reading and writing to streams; implementations are allowed
17to throw an :exc:`IOError` if they do not support a given operation.
18
19Extending :class:`IOBase` is :class:`RawIOBase` which deals simply with the
20reading and writing of raw bytes to a stream. :class:`FileIO` subclasses
21:class:`RawIOBase` to provide an interface to OS files.
22
23:class:`BufferedIOBase` deals with buffering on a raw byte stream
24(:class:`RawIOBase`). Its subclasses, :class:`BufferedWriter`,
25:class:`BufferedReader`, and :class:`BufferedRWPair` buffer streams that are
26readable, writable, and both respectively. :class:`BufferedRandom` provides a
27buffered interface to random access streams. :class:`BytesIO` is a simple
28stream of in-memory bytes.
29
Benjamin Peterson2c5f8282008-04-13 00:27:46 +000030Another :class:`IOBase` subclass, :class:`TextIOBase`, deals with the encoding
Georg Brandl014197c2008-04-09 18:40:51 +000031and decoding of streams into text. :class:`TextIOWrapper`, which extends it, is
32a buffered text interface to a buffered raw stream (:class:`BufferedIOBase`).
33Finally, :class:`StringIO` is a in-memory stream for text.
34
Benjamin Peterson2c5f8282008-04-13 00:27:46 +000035Argument names are not part of the specification, and only the arguments of
Benjamin Petersonb85a5842008-04-13 21:39:58 +000036:func:`open` are intended to be used as keyword arguments.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +000037
Georg Brandl014197c2008-04-09 18:40:51 +000038
39Module Interface
40----------------
41
42.. data:: DEFAULT_BUFFER_SIZE
43
44 An int containing the default buffer size used by the module's buffered I/O
Benjamin Petersonb85a5842008-04-13 21:39:58 +000045 classes. :func:`open` uses the file's blksize (as obtained by
Benjamin Peterson2c5f8282008-04-13 00:27:46 +000046 :func:`os.stat`) if possible.
Georg Brandl014197c2008-04-09 18:40:51 +000047
48.. function:: open(file[, mode[, buffering[, encoding[, errors[, newline[, closefd=True]]]]]])
49
Benjamin Petersondd219122008-04-11 21:17:32 +000050 Open *file* and return a stream. If the file cannot be opened, an
51 :exc:`IOError` is raised.
Georg Brandl014197c2008-04-09 18:40:51 +000052
Benjamin Petersondd219122008-04-11 21:17:32 +000053 *file* is either a string giving the name (and the path if the file isn't in
54 the current working directory) of the file to be opened or an integer file
55 descriptor of the file to be wrapped. (If a file descriptor is given, it is
56 closed when the returned I/O object is closed, unless *closefd* is set to
57 ``False``.)
Georg Brandl014197c2008-04-09 18:40:51 +000058
Benjamin Petersondd219122008-04-11 21:17:32 +000059 *mode* is an optional string that specifies the mode in which the file is
60 opened. It defaults to ``'r'`` which means open for reading in text mode.
61 Other common values are ``'w'`` for writing (truncating the file if it
62 already exists), and ``'a'`` for appending (which on *some* Unix systems,
63 means that *all* writes append to the end of the file regardless of the
64 current seek position). In text mode, if *encoding* is not specified the
65 encoding used is platform dependent. (For reading and writing raw bytes use
66 binary mode and leave *encoding* unspecified.) The available modes are:
Georg Brandl014197c2008-04-09 18:40:51 +000067
68 ========= ===============================================================
69 Character Meaning
70 --------- ---------------------------------------------------------------
71 ``'r'`` open for reading (default)
72 ``'w'`` open for writing, truncating the file first
73 ``'a'`` open for writing, appending to the end of the file if it exists
74 ``'b'`` binary mode
75 ``'t'`` text mode (default)
76 ``'+'`` open a disk file for updating (reading and writing)
77 ``'U'`` universal newline mode (for backwards compatibility; unneeded
78 for new code)
79 ========= ===============================================================
80
81 The default mode is ``'rt'`` (open for reading text). For binary random
82 access, the mode ``'w+b'`` opens and truncates the file to 0 bytes, while
83 ``'r+b'`` opens the file without truncation.
84
Benjamin Peterson2c5f8282008-04-13 00:27:46 +000085 Python distinguishes between files opened in binary and text modes, even when
86 the underlying operating system doesn't. Files opened in binary mode
87 (appending ``'b'`` to the *mode* argument) return contents as ``bytes``
88 objects without any decoding. In text mode (the default, or when ``'t'`` is
89 appended to the *mode* argument), the contents of the file are returned as
90 strings, the bytes having been first decoded using a platform-dependent
91 encoding or using the specified *encoding* if given.
Benjamin Petersondd219122008-04-11 21:17:32 +000092
93 *buffering* is an optional integer used to set the buffering policy. By
Benjamin Peterson2c5f8282008-04-13 00:27:46 +000094 default full buffering is on. Pass 0 to switch buffering off (only allowed
95 in binary mode), 1 to set line buffering, and an integer > 1 for full
96 buffering.
Georg Brandl014197c2008-04-09 18:40:51 +000097
98 *encoding* is the name of the encoding used to decode or encode the file.
Benjamin Petersondd219122008-04-11 21:17:32 +000099 This should only be used in text mode. The default encoding is platform
100 dependent, but any encoding supported by Python can be passed. See the
101 :mod:`codecs` module for the list of supported encodings.
Georg Brandl014197c2008-04-09 18:40:51 +0000102
Benjamin Petersonb85a5842008-04-13 21:39:58 +0000103 *errors* is an optional string that specifies how encoding and decoding
Christian Heimesa342c012008-04-20 21:01:16 +0000104 errors are to be handled. Pass ``'strict'`` to raise a :exc:`ValueError`
105 exception if there is an encoding error (the default of ``None`` has the same
106 effect), or pass ``'ignore'`` to ignore errors. (Note that ignoring encoding
107 errors can lead to data loss.) ``'replace'`` causes a replacement marker
108 (such as ``'?'``) to be inserted where there is malformed data. When
109 writing, ``'xmlcharrefreplace'`` (replace with the appropriate XML character
110 reference) or ``'backslashreplace'`` (replace with backslashed escape
111 sequences) can be used. Any other error handling name that has been
112 registered with :func:`codecs.register_error` is also valid.
Georg Brandl014197c2008-04-09 18:40:51 +0000113
114 *newline* controls how universal newlines works (it only applies to text
115 mode). It can be ``None``, ``''``, ``'\n'``, ``'\r'``, and ``'\r\n'``. It
116 works as follows:
117
118 * On input, if *newline* is ``None``, universal newlines mode is enabled.
119 Lines in the input can end in ``'\n'``, ``'\r'``, or ``'\r\n'``, and these
120 are translated into ``'\n'`` before being returned to the caller. If it is
121 ``''``, universal newline mode is enabled, but line endings are returned to
122 the caller untranslated. If it has any of the other legal values, input
123 lines are only terminated by the given string, and the line ending is
124 returned to the caller untranslated.
125
126 * On output, if *newline* is ``None``, any ``'\n'`` characters written are
127 translated to the system default line separator, :data:`os.linesep`. If
128 *newline* is ``''``, no translation takes place. If *newline* is any of
129 the other legal values, any ``'\n'`` characters written are translated to
130 the given string.
131
Benjamin Petersondd219122008-04-11 21:17:32 +0000132 If *closefd* is ``False``, the underlying file descriptor will be kept open
133 when the file is closed. This does not work when a file name is given and
134 must be ``True`` in that case.
Georg Brandl014197c2008-04-09 18:40:51 +0000135
Benjamin Petersonb85a5842008-04-13 21:39:58 +0000136 :func:`open` returns a file object whose type depends on the mode, and
Benjamin Petersondd219122008-04-11 21:17:32 +0000137 through which the standard file operations such as reading and writing are
Benjamin Petersonb85a5842008-04-13 21:39:58 +0000138 performed. When :func:`open` is used to open a file in a text mode (``'w'``,
139 ``'r'``, ``'wt'``, ``'rt'``, etc.), it returns a :class:`TextIOWrapper`.
140 When used to open a file in a binary mode, the returned class varies: in read
141 binary mode, it returns a :class:`BufferedReader`; in write binary and append
142 binary modes, it returns a :class:`BufferedWriter`, and in read/write mode,
143 it returns a :class:`BufferedRandom`.
Georg Brandl014197c2008-04-09 18:40:51 +0000144
145 It is also possible to use a string or bytearray as a file for both reading
Benjamin Petersondd219122008-04-11 21:17:32 +0000146 and writing. For strings :class:`StringIO` can be used like a file opened in
147 a text mode, and for bytes a :class:`BytesIO` can be used like a file opened
148 in a binary mode.
Georg Brandl014197c2008-04-09 18:40:51 +0000149
150
151.. exception:: BlockingIOError
152
153 Error raised when blocking would occur on a non-blocking stream. It inherits
154 :exc:`IOError`.
155
156 In addition to those of :exc:`IOError`, :exc:`BlockingIOError` has one
157 attribute:
158
159 .. attribute:: characters_written
160
161 An integer containing the number of characters written to the stream
162 before it blocked.
163
164
165.. exception:: UnsupportedOperation
166
167 An exception inheriting :exc:`IOError` and :exc:`ValueError` that is raised
168 when an unsupported operation is called on a stream.
169
170
171I/O Base Classes
172----------------
173
174.. class:: IOBase
175
176 The abstract base class for all I/O classes, acting on streams of bytes.
177 There is no public constructor.
178
179 This class provides dummy implementations for many methods that derived
180 classes can override selectively; the default implementations represent a
181 file that cannot be read, written or seeked.
182
183 Even though :class:`IOBase` does not declare :meth:`read`, :meth:`readinto`,
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000184 or :meth:`write` because their signatures will vary, implementations and
185 clients should consider those methods part of the interface. Also,
186 implementations may raise a :exc:`IOError` when operations they do not
187 support are called.
Georg Brandl014197c2008-04-09 18:40:51 +0000188
189 The basic type used for binary data read from or written to a file is
190 :class:`bytes`. :class:`bytearray`\s are accepted too, and in some cases
191 (such as :class:`readinto`) needed. Text I/O classes work with :class:`str`
192 data.
193
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000194 Note that calling any method (even inquiries) on a closed stream is
195 undefined. Implementations may raise :exc:`IOError` in this case.
Georg Brandl014197c2008-04-09 18:40:51 +0000196
197 IOBase (and its subclasses) support the iterator protocol, meaning that an
198 :class:`IOBase` object can be iterated over yielding the lines in a stream.
199
200 IOBase also supports the :keyword:`with` statement. In this example, *fp* is
201 closed after the suite of the with statment is complete::
202
203 with open('spam.txt', 'r') as fp:
204 fp.write('Spam and eggs!')
205
206 :class:`IOBase` provides these methods:
207
208 .. method:: close()
209
210 Flush and close this stream. This method has no effect if the file is
211 already closed.
212
213 .. attribute:: closed
214
215 True if the stream is closed.
216
217 .. method:: fileno()
218
219 Return the underlying file descriptor (an integer) of the stream, if it
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000220 exists. An :exc:`IOError` is raised if the IO object does not use a file
Georg Brandl014197c2008-04-09 18:40:51 +0000221 descriptor.
222
223 .. method:: flush()
224
Benjamin Petersonb85a5842008-04-13 21:39:58 +0000225 Flush the write buffers of the stream if applicable. This does nothing
226 for read-only and non-blocking streams.
Georg Brandl014197c2008-04-09 18:40:51 +0000227
228 .. method:: isatty()
229
230 Tell if a stream is interactive (connected to a terminal/tty device).
231
232 .. method:: readable()
233
234 Tell if a stream can be read from. If False, :meth:`read` will raise
235 :exc:`IOError`.
236
237 .. method:: readline([limit])
238
239 Read and return a line from the stream. If *limit* is specified, at most
240 *limit* bytes will be read.
241
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000242 The line terminator is always ``b'\n'`` for binary files; for text files,
Benjamin Petersonb85a5842008-04-13 21:39:58 +0000243 the *newlines* argument to :func:`open` can be used to select the line
Georg Brandl014197c2008-04-09 18:40:51 +0000244 terminator(s) recognized.
245
246 .. method:: readlines([hint])
247
248 Return a list of lines from the stream. *hint* can be specified to
249 control the number of lines read: no more lines will be read if the total
250 size (in bytes/characters) of all lines so far exceeds *hint*.
251
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000252 .. method:: seek(offset[, whence])
253
254 Change the stream position to byte offset *offset*. *offset* is
255 interpreted relative to the position indicated by *whence*. Values for
256 *whence* are:
257
258 * ``0`` -- start of stream (the default); *pos* should be zero or positive
259 * ``1`` -- current stream position; *pos* may be negative
260 * ``2`` -- end of stream; *pos* is usually negative
261
262 Return the new absolute position.
263
Georg Brandl014197c2008-04-09 18:40:51 +0000264 .. method:: seekable()
265
266 Tell if a stream supports random IO access. If ``False``, :meth:`seek`,
267 :meth:`tell` and :meth:`truncate` will raise :exc:`IOError`.
268
269 .. method:: tell()
270
271 Return an integer indicating the current stream position.
272
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000273 .. method:: truncate([pos])
274
275 Truncate the file to at most *pos* bytes. *pos* defaults to the current
276 file position, as returned by :meth:`tell`.
277
Georg Brandl014197c2008-04-09 18:40:51 +0000278 .. method:: writable()
279
280 Tell if a stream supports writing. If ``False``, :meth:`write` and
281 :meth:`truncate` will raise :exc:`IOError`.
282
283 .. method:: writelines(lines)
284
285 Write a list of lines to the stream. The lines will not be altered; they
286 must contain line separators.
287
288
289.. class:: RawIOBase
290
291 Base class for raw binary I/O. It inherits :class:`IOBase`. There is no
292 public constructor.
293
294 RawIOBase provides or overrides these methods in addition to those from
295 :class:`IOBase`:
296
Benjamin Petersonb47aace2008-04-09 21:38:38 +0000297 .. method:: read([n])
Georg Brandl014197c2008-04-09 18:40:51 +0000298
299 Read and return all bytes from the stream until EOF, or if *n* is
300 specified, up to *n* bytes. An empty bytes object is returned on EOF;
301 ``None`` is returned if the object is set not to block and has no data to
302 read.
303
Benjamin Petersonb47aace2008-04-09 21:38:38 +0000304 .. method:: readall()
Georg Brandl014197c2008-04-09 18:40:51 +0000305
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000306 Read and return all bytes from the stream until EOF, using multiple calls
307 to the stream.
308
309 .. method:: readinto(b)
310
311 Read up to len(b) bytes into bytearray *b* and return the number of bytes
312 read.
313
314 .. method:: write(b)
315
316 Write the given bytes, *b*, to the underlying raw stream and return the
317 number of bytes written (never less than ``len(b)``).
Georg Brandl014197c2008-04-09 18:40:51 +0000318
319
320Raw File I/O
321------------
322
323.. class:: FileIO(name[, mode])
324
325 :class:`FileIO` represents an OS file containing bytes data. It implements
326 the :class:`RawIOBase` interface (and therefore the :class:`IOBase`
327 interface, too).
328
329 The *mode* can be ``'r'``, ``'w'`` or ``'a'`` for reading (default), writing,
330 or appending. The file will be created if it doesn't exist when opened for
331 writing or appending; it will be truncated when opened for writing. Add a
332 ``'+'`` to the mode to allow simultaneous reading and writing.
333
334 :class:`FileIO` provides or overrides these methods in addition to those from
335 :class:`RawIOBase` and :class:`IOBase`:
336
337 .. attribute:: mode
338
339 The mode as given in the constructor.
340
341 .. attribute:: name
342
343 The file name.
344
345 .. method:: read([n])
346
347 Read and return bytes at most *n* bytes. Only one system call is made, so
348 less data than requested may be returned. In non-blocking mode, ``None``
349 is returned when no data is available.
350
351 .. method:: readall()
352
353 Read and return as bytes all the data from the file. As much as
354 immediately available is returned in non-blocking mode. If the EOF has
355 been reached, ``b''`` is returned.
356
357 .. method:: readinto(bytearray)
358
359 This method should not be used on :class:`FileIO` objects.
360
Georg Brandl014197c2008-04-09 18:40:51 +0000361 .. method:: write(b)
362
363 Write the bytes *b* to the file, and return the number actually written.
364 Only one system call is made, so not all of the data may be written.
365
366
367Buffered Streams
368----------------
369
370.. class:: BufferedIOBase
371
372 Base class for streams that support buffering. It inherits :class:`IOBase`.
373 There is no public constructor.
374
375 The main difference with :class:`RawIOBase` is that the :meth:`read` method
376 supports omitting the *size* argument, and does not have a default
377 implementation that defers to :meth:`readinto`.
378
379 In addition, :meth:`read`, :meth:`readinto`, and :meth:`write` may raise
380 :exc:`BlockingIOError` if the underlying raw stream is in non-blocking mode
381 and not ready; unlike their raw counterparts, they will never return
382 ``None``.
383
384 A typical implementation should not inherit from a :class:`RawIOBase`
385 implementation, but wrap one like :class:`BufferedWriter` and
386 :class:`BufferedReader`.
387
388 :class:`BufferedIOBase` provides or overrides these methods in addition to
389 those from :class:`IOBase`:
390
391 .. method:: read([n])
392
393 Read and return up to *n* bytes. If the argument is omitted, ``None``, or
394 negative, data is read and returned until EOF is reached. An empty bytes
395 object is returned if the stream is already at EOF.
396
397 If the argument is positive, and the underlying raw stream is not
398 interactive, multiple raw reads may be issued to satisfy the byte count
399 (unless EOF is reached first). But for interactive raw streams, at most
400 one raw read will be issued, and a short result does not imply that EOF is
401 imminent.
402
403 A :exc:`BlockingIOError` is raised if the underlying raw stream has no
404 data at the moment.
405
406 .. method:: readinto(b)
407
408 Read up to len(b) bytes into bytearray *b* and return the number of bytes
409 read.
410
411 Like :meth:`read`, multiple reads may be issued to the underlying raw
412 stream, unless the latter is 'interactive.'
413
414 A :exc:`BlockingIOError` is raised if the underlying raw stream has no
415 data at the moment.
416
Georg Brandl014197c2008-04-09 18:40:51 +0000417 .. method:: write(b)
418
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000419 Write the given bytes, *b*, to the underlying raw stream and return the
420 number of bytes written (never less than ``len(b)``).
Georg Brandl014197c2008-04-09 18:40:51 +0000421
422 A :exc:`BlockingIOError` is raised if the buffer is full, and the
423 underlying raw stream cannot accept more data at the moment.
424
425
426.. class:: BytesIO([initial_bytes])
427
428 A stream implementation using an in-memory bytes buffer. It inherits
429 :class:`BufferedIOBase`.
430
431 The argument *initial_bytes* is an optional initial bytearray.
432
433 :class:`BytesIO` provides or overrides these methods in addition to those
434 from :class:`BufferedIOBase` and :class:`IOBase`:
435
436 .. method:: getvalue()
437
438 Return the bytes value of the buffer.
439
440 .. method:: read1()
441
Benjamin Peterson9efcc4b2008-04-14 21:30:21 +0000442 In :class:`BytesIO`, this is the same as :meth:`read`.
Georg Brandl014197c2008-04-09 18:40:51 +0000443
444 .. method:: truncate([pos])
445
446 Truncate the file to at most *pos* bytes. *pos* defaults to the current
Benjamin Peterson9efcc4b2008-04-14 21:30:21 +0000447 stream position, as returned by :meth:`tell`.
Georg Brandl014197c2008-04-09 18:40:51 +0000448
449
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000450.. class:: BufferedReader(raw[, buffer_size])
Georg Brandl014197c2008-04-09 18:40:51 +0000451
Benjamin Peterson13d4a612008-04-13 23:46:27 +0000452 A buffer for a readable, sequential :class:`RawIOBase` object. It inherits
Georg Brandl014197c2008-04-09 18:40:51 +0000453 :class:`BufferedIOBase`.
454
455 The constructor creates a :class:`BufferedReader` for the given readable
456 *raw* stream and *buffer_size*. If *buffer_size* is omitted,
457 :data:`DEFAULT_BUFFER_SIZE` is used.
458
459 :class:`BufferedReader` provides or overrides these methods in addition to
460 those from :class:`BufferedIOBase` and :class:`IOBase`:
461
462 .. method:: peek([n])
463
464 Return bytes from a buffer without advancing the position. The argument
465 indicates a desired minimal number of bytes; only one read on the raw
466 stream is done to satisfy it. More than the buffer's size is never
467 returned.
468
469 .. method:: read([n])
470
471 Read and return *n* bytes, or if *n* is not given or negative, until EOF
472 or if the read call would block in non-blocking mode.
473
474 .. method:: read1(n)
475
476 Read and return up to *n* bytes with only one call on the raw stream. If
477 at least one byte is buffered, only buffered bytes are returned.
478 Otherwise, one raw stream read call is made.
479
480
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000481.. class:: BufferedWriter(raw[, buffer_size[, max_buffer_size]])
Georg Brandl014197c2008-04-09 18:40:51 +0000482
483 A buffer for a writeable sequential RawIO object. It inherits
484 :class:`BufferedIOBase`.
485
486 The constructor creates a :class:`BufferedWriter` for the given writeable
487 *raw* stream. If the *buffer_size* is not given, it defaults to
488 :data:`DEAFULT_BUFFER_SIZE`. If *max_buffer_size* is omitted, it defaults to
489 twice the buffer size.
490
491 :class:`BufferedWriter` provides or overrides these methods in addition to
492 those from :class:`BufferedIOBase` and :class:`IOBase`:
493
494 .. method:: flush()
495
496 Force bytes held in the buffer into the raw stream. A
497 :exc:`BlockingIOError` is be raised if the raw stream blocks.
498
499 .. method:: write(b)
500
501 Write bytes *b* onto the raw stream and return the number written. A
502 :exc:`BlockingIOError` is raised when the raw stream blocks.
503
504
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000505.. class:: BufferedRWPair(reader, writer[, buffer_size[, max_buffer_size]])
Georg Brandl014197c2008-04-09 18:40:51 +0000506
507 A buffered writer and reader object together for a raw stream that can be
508 written and read from. It has and supports both :meth:`read`, :meth:`write`,
509 and their variants. This is useful for such applications such as sockets and
510 two-way pipes. It inherits :class:`BufferedIOBase`.
511
512 *reader* and *writer* are :class:`RawIOBase` objects that are readable and
513 writeable respectively. If the *buffer_size* is omitted it defaults to
514 :data:`DEFAULT_BUFFER_SIZE`. The *max_buffer_size* (for the buffered writer)
515 defaults to twice the buffer size.
516
517 :class:`BufferedRWPair` implements all of :class:`BufferedIOBase`\'s methods.
518
519
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000520.. class:: BufferedRandom(raw[, buffer_size[, max_buffer_size]])
Georg Brandl014197c2008-04-09 18:40:51 +0000521
522 A buffered interface to random access streams. It inherits
523 :class:`BufferedReader` and :class:`BufferedWriter`.
524
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000525 The constructor creates a reader and writer for a seekable raw stream, given
Georg Brandl014197c2008-04-09 18:40:51 +0000526 in the first argument. If the *buffer_size* is omitted it defaults to
527 :data:`DEFAULT_BUFFER_SIZE`. The *max_buffer_size* (for the buffered writer)
528 defaults to twice the buffer size.
529
530 :class:`BufferedRandom` is capable of anything :class:`BufferedReader` or
531 :class:`BufferedWriter` can do.
532
533
534Text I/O
535--------
536
537.. class:: TextIOBase
538
539 Base class for text streams. This class provides a character and line based
540 interface to stream I/O. There is no :meth:`readinto` method because
541 Python's character strings are immutable. It inherits :class:`IOBase`.
542 There is no public constructor.
543
544 :class:`TextIOBase` provides or overrides these methods in addition to those
545 from :class:`IOBase`:
546
547 .. attribute:: encoding
548
549 Return the name of the encoding used to decode the stream's bytes into
550 strings, and to encode strings into bytes.
551
552 .. attribute:: newlines
553
554 Return a string, tuple of strings, or ``None`` indicating the newlines
555 translated so far.
556
557 .. method:: read(n)
558
559 Read and return at most *n* characters from the stream. If *n* is
560 negative or ``None``, read to EOF.
561
562 .. method:: readline()
563
564 Read until newline or EOF and return. If the stream is already at EOF, an
565 empty stream is returned.
566
Georg Brandl014197c2008-04-09 18:40:51 +0000567 .. method:: write(s)
568
569 Write string *s* to the stream and return the number of characters
570 written.
571
572
573.. class:: TextIOWrapper(buffer[, encoding[, errors[, newline[, line_buffering]]]])
574
575 A buffered text stream over a :class:`BufferedIOBase` raw stream, *buffer*.
576 It inherits :class:`TextIOBase`.
577
578 *encoding* gives the name of the encoding that the stream will be decoded or
579 encoded with. It defaults to :func:`locale.getpreferredencoding`.
580
Benjamin Petersonb85a5842008-04-13 21:39:58 +0000581 *errors* is an optional string that specifies how encoding and decoding
582 errors are to be handled. Pass ``'strict'`` to raise a :exc:`ValueError`
583 exception if there is an encoding error (the default of ``None`` has the same
584 effect), or pass ``'ignore'`` to ignore errors. (Note that ignoring encoding
585 errors can lead to data loss.) ``'replace'`` causes a replacement marker
Christian Heimesa342c012008-04-20 21:01:16 +0000586 (such as ``'?'``) to be inserted where there is malformed data. When
587 writing, ``'xmlcharrefreplace'`` (replace with the appropriate XML character
588 reference) or ``'backslashreplace'`` (replace with backslashed escape
589 sequences) can be used. Any other error handling name that has been
590 registered with :func:`codecs.register_error` is also valid.
Georg Brandl014197c2008-04-09 18:40:51 +0000591
592 *newline* can be ``None``, ``''``, ``'\n'``, ``'\r'``, or ``'\r\n'``. It
593 controls the handling of line endings. If it is ``None``, universal newlines
594 is enabled. With this enabled, on input, the lines endings ``'\n'``,
595 ``'\r'``, or ``'\r\n'`` are translated to ``'\n'`` before being returned to
596 the caller. Conversely, on output, ``'\n'`` is translated to the system
597 default line seperator, :data:`os.linesep`. If *newline* is any other of its
598 legal values, that newline becomes the newline when the file is read and it
599 is returned untranslated. On output, ``'\n'`` is converted to the *newline*.
600
601 If *line_buffering* is ``True``, :meth:`flush` is implied when a call to
602 write contains a newline character.
603
604 :class:`TextIOWrapper` provides these methods in addition to those of
605 :class:`TextIOBase` and its parents:
606
607 .. attribute:: errors
608
609 The encoding and decoding error setting.
610
611 .. attribute:: line_buffering
612
613 Whether line buffering is enabled.
614
615
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000616.. class:: StringIO([initial_value[, encoding[, errors[, newline]]]])
Georg Brandl014197c2008-04-09 18:40:51 +0000617
618 An in-memory stream for text. It in inherits :class:`TextIOWrapper`.
619
620 Create a new StringIO stream with an inital value, encoding, error handling,
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000621 and newline setting. See :class:`TextIOWrapper`\'s constructor for more
Georg Brandl014197c2008-04-09 18:40:51 +0000622 information.
623
624 :class:`StringIO` provides these methods in addition to those from
625 :class:`TextIOWrapper` and its parents:
626
627 .. method:: getvalue()
628
629 Return a str representation of the contents of the internal buffer.
630
631
632.. class:: IncrementalNewlineDecoder
633
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000634 A helper codec that decodes newlines for universal newlines mode. It
635 inherits :class:`codecs.IncrementalDecoder`.
Georg Brandl014197c2008-04-09 18:40:51 +0000636