blob: a8a4068c7f38be821c14e53c5fcba8a4dfc90bc2 [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>
Georg Brandl686d53e2009-01-14 00:08:09 +00009.. sectionauthor:: Benjamin Peterson <benjamin@python.org>
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +000010.. versionadded:: 2.6
11
12The :mod:`io` module provides the Python interfaces to stream handling. The
Georg Brandl4ae4f872009-10-27 14:37:48 +000013built-in :func:`open` function is defined in this module.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +000014
15At the top of the I/O hierarchy is the abstract base class :class:`IOBase`. It
16defines the basic interface to a stream. Note, however, that there is no
Jesus Cea585ad8a2009-07-02 15:37:21 +000017separation between reading and writing to streams; implementations are allowed
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +000018to throw an :exc:`IOError` if they do not support a given operation.
19
20Extending :class:`IOBase` is :class:`RawIOBase` which deals simply with the
21reading and writing of raw bytes to a stream. :class:`FileIO` subclasses
Benjamin Petersonad9f6292008-04-21 11:57:40 +000022:class:`RawIOBase` to provide an interface to files in the machine's
23file system.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +000024
25:class:`BufferedIOBase` deals with buffering on a raw byte stream
26(:class:`RawIOBase`). Its subclasses, :class:`BufferedWriter`,
27:class:`BufferedReader`, and :class:`BufferedRWPair` buffer streams that are
Benjamin Petersonad9f6292008-04-21 11:57:40 +000028readable, writable, and both readable and writable.
29:class:`BufferedRandom` provides a buffered interface to random access
30streams. :class:`BytesIO` is a simple stream of in-memory bytes.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +000031
Benjamin Petersonad9f6292008-04-21 11:57:40 +000032Another :class:`IOBase` subclass, :class:`TextIOBase`, deals with
33streams whose bytes represent text, and handles encoding and decoding
34from and to strings. :class:`TextIOWrapper`, which extends it, is a
35buffered text interface to a buffered raw stream
36(:class:`BufferedIOBase`). Finally, :class:`StringIO` is an in-memory
37stream for text.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +000038
39Argument names are not part of the specification, and only the arguments of
Georg Brandl0dfdf002009-10-27 14:36:50 +000040:func:`.open` are intended to be used as keyword arguments.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +000041
42
43Module Interface
44----------------
45
46.. data:: DEFAULT_BUFFER_SIZE
47
48 An int containing the default buffer size used by the module's buffered I/O
Georg Brandl0dfdf002009-10-27 14:36:50 +000049 classes. :func:`.open` uses the file's blksize (as obtained by
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +000050 :func:`os.stat`) if possible.
51
52.. function:: open(file[, mode[, buffering[, encoding[, errors[, newline[, closefd=True]]]]]])
53
54 Open *file* and return a stream. If the file cannot be opened, an
55 :exc:`IOError` is raised.
56
57 *file* is either a string giving the name (and the path if the file isn't in
Benjamin Petersonad9f6292008-04-21 11:57:40 +000058 the current working directory) of the file to be opened or a file
59 descriptor of the file to be opened. (If a file descriptor is given,
60 for example, from :func:`os.fdopen`, it is closed when the returned
61 I/O object is closed, unless *closefd* is set to ``False``.)
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +000062
63 *mode* is an optional string that specifies the mode in which the file is
64 opened. It defaults to ``'r'`` which means open for reading in text mode.
65 Other common values are ``'w'`` for writing (truncating the file if it
66 already exists), and ``'a'`` for appending (which on *some* Unix systems,
67 means that *all* writes append to the end of the file regardless of the
68 current seek position). In text mode, if *encoding* is not specified the
69 encoding used is platform dependent. (For reading and writing raw bytes use
70 binary mode and leave *encoding* unspecified.) The available modes are:
71
72 ========= ===============================================================
73 Character Meaning
74 --------- ---------------------------------------------------------------
75 ``'r'`` open for reading (default)
76 ``'w'`` open for writing, truncating the file first
77 ``'a'`` open for writing, appending to the end of the file if it exists
78 ``'b'`` binary mode
79 ``'t'`` text mode (default)
80 ``'+'`` open a disk file for updating (reading and writing)
Benjamin Petersonad9f6292008-04-21 11:57:40 +000081 ``'U'`` universal newline mode (for backwards compatibility; should
82 not be used in new code)
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +000083 ========= ===============================================================
84
85 The default mode is ``'rt'`` (open for reading text). For binary random
86 access, the mode ``'w+b'`` opens and truncates the file to 0 bytes, while
87 ``'r+b'`` opens the file without truncation.
88
89 Python distinguishes between files opened in binary and text modes, even when
90 the underlying operating system doesn't. Files opened in binary mode
Benjamin Petersonad9f6292008-04-21 11:57:40 +000091 (including ``'b'`` in the *mode* argument) return contents as ``bytes``
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +000092 objects without any decoding. In text mode (the default, or when ``'t'`` is
Benjamin Petersonad9f6292008-04-21 11:57:40 +000093 included in the *mode* argument), the contents of the file are returned as
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +000094 strings, the bytes having been first decoded using a platform-dependent
95 encoding or using the specified *encoding* if given.
96
Antoine Pitroub9767262009-12-19 21:03:36 +000097 *buffering* is an optional integer used to set the buffering policy.
98 Pass 0 to switch buffering off (only allowed in binary mode), 1 to select
99 line buffering (only usable in text mode), and an integer > 1 to indicate
100 the size of a fixed-size chunk buffer. When no *buffering* argument is
101 given, the default buffering policy works as follows:
102
103 * Binary files are buffered in fixed-size chunks; the size of the buffer
104 is chosen using a heuristic trying to determine the underlying device's
105 "block size" and falling back on :attr:`DEFAULT_BUFFER_SIZE`.
106 On many systems, the buffer will typically be 4096 or 8192 bytes long.
107
108 * "Interactive" text files (files for which :meth:`isatty` returns True)
109 use line buffering. Other text files use the policy described above
110 for binary files.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000111
112 *encoding* is the name of the encoding used to decode or encode the file.
113 This should only be used in text mode. The default encoding is platform
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000114 dependent, but any encoding supported by Python can be used. See the
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000115 :mod:`codecs` module for the list of supported encodings.
116
Benjamin Peterson53be57e2008-04-19 19:34:05 +0000117 *errors* is an optional string that specifies how encoding and decoding
Benjamin Petersona7d09032008-04-19 19:47:34 +0000118 errors are to be handled. Pass ``'strict'`` to raise a :exc:`ValueError`
119 exception if there is an encoding error (the default of ``None`` has the same
120 effect), or pass ``'ignore'`` to ignore errors. (Note that ignoring encoding
121 errors can lead to data loss.) ``'replace'`` causes a replacement marker
122 (such as ``'?'``) to be inserted where there is malformed data. When
123 writing, ``'xmlcharrefreplace'`` (replace with the appropriate XML character
124 reference) or ``'backslashreplace'`` (replace with backslashed escape
125 sequences) can be used. Any other error handling name that has been
126 registered with :func:`codecs.register_error` is also valid.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000127
128 *newline* controls how universal newlines works (it only applies to text
129 mode). It can be ``None``, ``''``, ``'\n'``, ``'\r'``, and ``'\r\n'``. It
130 works as follows:
131
132 * On input, if *newline* is ``None``, universal newlines mode is enabled.
133 Lines in the input can end in ``'\n'``, ``'\r'``, or ``'\r\n'``, and these
134 are translated into ``'\n'`` before being returned to the caller. If it is
135 ``''``, universal newline mode is enabled, but line endings are returned to
136 the caller untranslated. If it has any of the other legal values, input
137 lines are only terminated by the given string, and the line ending is
138 returned to the caller untranslated.
139
140 * On output, if *newline* is ``None``, any ``'\n'`` characters written are
141 translated to the system default line separator, :data:`os.linesep`. If
142 *newline* is ``''``, no translation takes place. If *newline* is any of
143 the other legal values, any ``'\n'`` characters written are translated to
144 the given string.
145
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000146 If *closefd* is ``False`` and a file descriptor rather than a
147 filename was given, the underlying file descriptor will be kept open
148 when the file is closed. If a filename is given *closefd* has no
149 effect but must be ``True`` (the default).
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000150
Georg Brandl0dfdf002009-10-27 14:36:50 +0000151 The type of file object returned by the :func:`.open` function depends
152 on the mode. When :func:`.open` is used to open a file in a text mode
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000153 (``'w'``, ``'r'``, ``'wt'``, ``'rt'``, etc.), it returns a
154 :class:`TextIOWrapper`. When used to open a file in a binary mode,
155 the returned class varies: in read binary mode, it returns a
156 :class:`BufferedReader`; in write binary and append binary modes, it
157 returns a :class:`BufferedWriter`, and in read/write mode, it returns
158 a :class:`BufferedRandom`.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000159
160 It is also possible to use a string or bytearray as a file for both reading
161 and writing. For strings :class:`StringIO` can be used like a file opened in
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000162 a text mode, and for bytearrays a :class:`BytesIO` can be used like a
163 file opened in a binary mode.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000164
165
166.. exception:: BlockingIOError
167
168 Error raised when blocking would occur on a non-blocking stream. It inherits
169 :exc:`IOError`.
170
171 In addition to those of :exc:`IOError`, :exc:`BlockingIOError` has one
172 attribute:
173
174 .. attribute:: characters_written
175
176 An integer containing the number of characters written to the stream
177 before it blocked.
178
179
180.. exception:: UnsupportedOperation
181
182 An exception inheriting :exc:`IOError` and :exc:`ValueError` that is raised
183 when an unsupported operation is called on a stream.
184
185
186I/O Base Classes
187----------------
188
189.. class:: IOBase
190
191 The abstract base class for all I/O classes, acting on streams of bytes.
192 There is no public constructor.
193
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000194 This class provides empty abstract implementations for many methods
195 that derived classes can override selectively; the default
196 implementations represent a file that cannot be read, written or
197 seeked.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000198
199 Even though :class:`IOBase` does not declare :meth:`read`, :meth:`readinto`,
200 or :meth:`write` because their signatures will vary, implementations and
201 clients should consider those methods part of the interface. Also,
202 implementations may raise a :exc:`IOError` when operations they do not
203 support are called.
204
205 The basic type used for binary data read from or written to a file is
206 :class:`bytes`. :class:`bytearray`\s are accepted too, and in some cases
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000207 (such as :class:`readinto`) required. Text I/O classes work with
208 :class:`str` data.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000209
210 Note that calling any method (even inquiries) on a closed stream is
211 undefined. Implementations may raise :exc:`IOError` in this case.
212
213 IOBase (and its subclasses) support the iterator protocol, meaning that an
214 :class:`IOBase` object can be iterated over yielding the lines in a stream.
215
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000216 IOBase is also a context manager and therefore supports the
217 :keyword:`with` statement. In this example, *file* is closed after the
218 :keyword:`with` statement's suite is finished---even if an exception occurs::
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000219
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000220 with open('spam.txt', 'w') as file:
221 file.write('Spam and eggs!')
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000222
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000223 :class:`IOBase` provides these data attributes and methods:
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000224
225 .. method:: close()
226
Georg Brandld2094602008-12-05 08:51:30 +0000227 Flush and close this stream. This method has no effect if the file is
Georg Brandl734373c2009-01-03 21:55:17 +0000228 already closed. Once the file is closed, any operation on the file
Georg Brandld2094602008-12-05 08:51:30 +0000229 (e.g. reading or writing) will raise an :exc:`IOError`. The internal
230 file descriptor isn't closed if *closefd* was False.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000231
232 .. attribute:: closed
233
234 True if the stream is closed.
235
236 .. method:: fileno()
237
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000238 Return the underlying file descriptor (an integer) of the stream if it
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000239 exists. An :exc:`IOError` is raised if the IO object does not use a file
240 descriptor.
241
242 .. method:: flush()
243
Benjamin Peterson53be57e2008-04-19 19:34:05 +0000244 Flush the write buffers of the stream if applicable. This does nothing
245 for read-only and non-blocking streams.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000246
247 .. method:: isatty()
248
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000249 Return ``True`` if the stream is interactive (i.e., connected to
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000250 a terminal/tty device).
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000251
252 .. method:: readable()
253
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000254 Return ``True`` if the stream can be read from. If False, :meth:`read`
255 will raise :exc:`IOError`.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000256
257 .. method:: readline([limit])
258
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000259 Read and return one line from the stream. If *limit* is specified, at
260 most *limit* bytes will be read.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000261
262 The line terminator is always ``b'\n'`` for binary files; for text files,
Georg Brandl0dfdf002009-10-27 14:36:50 +0000263 the *newlines* argument to :func:`.open` can be used to select the line
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000264 terminator(s) recognized.
265
266 .. method:: readlines([hint])
267
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000268 Read and return a list of lines from the stream. *hint* can be specified
269 to control the number of lines read: no more lines will be read if the
270 total size (in bytes/characters) of all lines so far exceeds *hint*.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000271
272 .. method:: seek(offset[, whence])
273
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000274 Change the stream position to the given byte *offset*. *offset* is
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000275 interpreted relative to the position indicated by *whence*. Values for
276 *whence* are:
277
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000278 * ``0`` -- start of the stream (the default); *offset* should be zero or positive
279 * ``1`` -- current stream position; *offset* may be negative
280 * ``2`` -- end of the stream; *offset* is usually negative
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000281
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000282 Return the new absolute position.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000283
284 .. method:: seekable()
285
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000286 Return ``True`` if the stream supports random access. If ``False``,
287 :meth:`seek`, :meth:`tell` and :meth:`truncate` will raise :exc:`IOError`.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000288
289 .. method:: tell()
290
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000291 Return the current stream position.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000292
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000293 .. method:: truncate([size])
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000294
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000295 Truncate the file to at most *size* bytes. *size* defaults to the current
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000296 file position, as returned by :meth:`tell`.
297
298 .. method:: writable()
299
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000300 Return ``True`` if the stream supports writing. If ``False``,
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000301 :meth:`write` and :meth:`truncate` will raise :exc:`IOError`.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000302
303 .. method:: writelines(lines)
304
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000305 Write a list of lines to the stream. Line separators are not added, so it
306 is usual for each of the lines provided to have a line separator at the
307 end.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000308
309
310.. class:: RawIOBase
311
312 Base class for raw binary I/O. It inherits :class:`IOBase`. There is no
313 public constructor.
314
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000315 In addition to the attributes and methods from :class:`IOBase`,
316 RawIOBase provides the following methods:
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000317
318 .. method:: read([n])
319
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000320 Read and return all the bytes from the stream until EOF, or if *n* is
321 specified, up to *n* bytes. Only one system call is ever made. An empty
322 bytes object is returned on EOF; ``None`` is returned if the object is set
323 not to block and has no data to read.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000324
325 .. method:: readall()
326
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000327 Read and return all the bytes from the stream until EOF, using multiple
328 calls to the stream if necessary.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000329
330 .. method:: readinto(b)
331
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000332 Read up to len(b) bytes into bytearray *b* and return the number of bytes
333 read.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000334
335 .. method:: write(b)
336
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000337 Write the given bytes or bytearray object, *b*, to the underlying raw
338 stream and return the number of bytes written (This is never less than
339 ``len(b)``, since if the write fails, an :exc:`IOError` will be raised).
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000340
341
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000342.. class:: BufferedIOBase
343
344 Base class for streams that support buffering. It inherits :class:`IOBase`.
345 There is no public constructor.
346
347 The main difference with :class:`RawIOBase` is that the :meth:`read` method
348 supports omitting the *size* argument, and does not have a default
349 implementation that defers to :meth:`readinto`.
350
351 In addition, :meth:`read`, :meth:`readinto`, and :meth:`write` may raise
352 :exc:`BlockingIOError` if the underlying raw stream is in non-blocking mode
353 and not ready; unlike their raw counterparts, they will never return
354 ``None``.
355
356 A typical implementation should not inherit from a :class:`RawIOBase`
357 implementation, but wrap one like :class:`BufferedWriter` and
358 :class:`BufferedReader`.
359
360 :class:`BufferedIOBase` provides or overrides these methods in addition to
361 those from :class:`IOBase`:
362
363 .. method:: read([n])
364
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000365 Read and return up to *n* bytes. If the argument is omitted, ``None``, or
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000366 negative, data is read and returned until EOF is reached. An empty bytes
367 object is returned if the stream is already at EOF.
368
369 If the argument is positive, and the underlying raw stream is not
370 interactive, multiple raw reads may be issued to satisfy the byte count
371 (unless EOF is reached first). But for interactive raw streams, at most
372 one raw read will be issued, and a short result does not imply that EOF is
373 imminent.
374
375 A :exc:`BlockingIOError` is raised if the underlying raw stream has no
376 data at the moment.
377
378 .. method:: readinto(b)
379
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000380 Read up to len(b) bytes into bytearray *b* and return the number of bytes
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000381 read.
382
383 Like :meth:`read`, multiple reads may be issued to the underlying raw
384 stream, unless the latter is 'interactive.'
385
386 A :exc:`BlockingIOError` is raised if the underlying raw stream has no
387 data at the moment.
388
389 .. method:: write(b)
390
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000391 Write the given bytes or bytearray object, *b*, to the underlying raw
392 stream and return the number of bytes written (never less than ``len(b)``,
393 since if the write fails an :exc:`IOError` will be raised).
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000394
395 A :exc:`BlockingIOError` is raised if the buffer is full, and the
396 underlying raw stream cannot accept more data at the moment.
397
398
Georg Brandl4f8084e2009-10-27 13:20:10 +0000399Raw File I/O
400------------
401
402.. class:: FileIO(name[, mode])
403
404 :class:`FileIO` represents a file containing bytes data. It implements
405 the :class:`RawIOBase` interface (and therefore the :class:`IOBase`
406 interface, too).
407
408 The *mode* can be ``'r'``, ``'w'`` or ``'a'`` for reading (default), writing,
409 or appending. The file will be created if it doesn't exist when opened for
410 writing or appending; it will be truncated when opened for writing. Add a
411 ``'+'`` to the mode to allow simultaneous reading and writing.
412
413 In addition to the attributes and methods from :class:`IOBase` and
414 :class:`RawIOBase`, :class:`FileIO` provides the following data
415 attributes and methods:
416
417 .. attribute:: mode
418
419 The mode as given in the constructor.
420
421 .. attribute:: name
422
423 The file name. This is the file descriptor of the file when no name is
424 given in the constructor.
425
426 .. method:: read([n])
427
428 Read and return at most *n* bytes. Only one system call is made, so it is
429 possible that less data than was requested is returned. Use :func:`len`
430 on the returned bytes object to see how many bytes were actually returned.
431 (In non-blocking mode, ``None`` is returned when no data is available.)
432
433 .. method:: readall()
434
435 Read and return the entire file's contents in a single bytes object. As
436 much as immediately available is returned in non-blocking mode. If the
437 EOF has been reached, ``b''`` is returned.
438
439 .. method:: write(b)
440
441 Write the bytes or bytearray object, *b*, to the file, and return
442 the number actually written. Only one system call is made, so it
443 is possible that only some of the data is written.
444
445 Note that the inherited ``readinto()`` method should not be used on
446 :class:`FileIO` objects.
447
448
449Buffered Streams
450----------------
451
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000452.. class:: BytesIO([initial_bytes])
453
454 A stream implementation using an in-memory bytes buffer. It inherits
455 :class:`BufferedIOBase`.
456
457 The argument *initial_bytes* is an optional initial bytearray.
458
459 :class:`BytesIO` provides or overrides these methods in addition to those
460 from :class:`BufferedIOBase` and :class:`IOBase`:
461
462 .. method:: getvalue()
463
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000464 Return ``bytes`` containing the entire contents of the buffer.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000465
466 .. method:: read1()
467
Benjamin Peterson53be57e2008-04-19 19:34:05 +0000468 In :class:`BytesIO`, this is the same as :meth:`read`.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000469
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000470 .. method:: truncate([size])
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000471
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000472 Truncate the buffer to at most *size* bytes. *size* defaults to the
473 current stream position, as returned by :meth:`tell`.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000474
475
476.. class:: BufferedReader(raw[, buffer_size])
477
Benjamin Peterson53be57e2008-04-19 19:34:05 +0000478 A buffer for a readable, sequential :class:`RawIOBase` object. It inherits
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000479 :class:`BufferedIOBase`.
480
481 The constructor creates a :class:`BufferedReader` for the given readable
482 *raw* stream and *buffer_size*. If *buffer_size* is omitted,
483 :data:`DEFAULT_BUFFER_SIZE` is used.
484
485 :class:`BufferedReader` provides or overrides these methods in addition to
486 those from :class:`BufferedIOBase` and :class:`IOBase`:
487
488 .. method:: peek([n])
489
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000490 Return 1 (or *n* if specified) bytes from a buffer without advancing the
491 position. Only a single read on the raw stream is done to satisfy the
492 call. The number of bytes returned may be less than requested since at
493 most all the buffer's bytes from the current position to the end are
494 returned.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000495
496 .. method:: read([n])
497
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000498 Read and return *n* bytes, or if *n* is not given or negative, until EOF
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000499 or if the read call would block in non-blocking mode.
500
501 .. method:: read1(n)
502
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000503 Read and return up to *n* bytes with only one call on the raw stream. If
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000504 at least one byte is buffered, only buffered bytes are returned.
505 Otherwise, one raw stream read call is made.
506
507
508.. class:: BufferedWriter(raw[, buffer_size[, max_buffer_size]])
509
510 A buffer for a writeable sequential RawIO object. It inherits
511 :class:`BufferedIOBase`.
512
513 The constructor creates a :class:`BufferedWriter` for the given writeable
514 *raw* stream. If the *buffer_size* is not given, it defaults to
515 :data:`DEAFULT_BUFFER_SIZE`. If *max_buffer_size* is omitted, it defaults to
516 twice the buffer size.
517
518 :class:`BufferedWriter` provides or overrides these methods in addition to
519 those from :class:`BufferedIOBase` and :class:`IOBase`:
520
521 .. method:: flush()
522
523 Force bytes held in the buffer into the raw stream. A
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000524 :exc:`BlockingIOError` should be raised if the raw stream blocks.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000525
526 .. method:: write(b)
527
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000528 Write the bytes or bytearray object, *b*, onto the raw stream and return
529 the number of bytes written. A :exc:`BlockingIOError` is raised when the
530 raw stream blocks.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000531
532
533.. class:: BufferedRWPair(reader, writer[, buffer_size[, max_buffer_size]])
534
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000535 A combined buffered writer and reader object for a raw stream that can be
536 written to and read from. It has and supports both :meth:`read`, :meth:`write`,
537 and their variants. This is useful for sockets and two-way pipes.
538 It inherits :class:`BufferedIOBase`.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000539
540 *reader* and *writer* are :class:`RawIOBase` objects that are readable and
541 writeable respectively. If the *buffer_size* is omitted it defaults to
542 :data:`DEFAULT_BUFFER_SIZE`. The *max_buffer_size* (for the buffered writer)
543 defaults to twice the buffer size.
544
545 :class:`BufferedRWPair` implements all of :class:`BufferedIOBase`\'s methods.
546
547
548.. class:: BufferedRandom(raw[, buffer_size[, max_buffer_size]])
549
550 A buffered interface to random access streams. It inherits
551 :class:`BufferedReader` and :class:`BufferedWriter`.
552
553 The constructor creates a reader and writer for a seekable raw stream, given
554 in the first argument. If the *buffer_size* is omitted it defaults to
555 :data:`DEFAULT_BUFFER_SIZE`. The *max_buffer_size* (for the buffered writer)
556 defaults to twice the buffer size.
557
558 :class:`BufferedRandom` is capable of anything :class:`BufferedReader` or
559 :class:`BufferedWriter` can do.
560
561
562Text I/O
563--------
564
565.. class:: TextIOBase
566
567 Base class for text streams. This class provides a character and line based
568 interface to stream I/O. There is no :meth:`readinto` method because
569 Python's character strings are immutable. It inherits :class:`IOBase`.
570 There is no public constructor.
571
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000572 :class:`TextIOBase` provides or overrides these data attributes and
573 methods in addition to those from :class:`IOBase`:
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000574
575 .. attribute:: encoding
576
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000577 The name of the encoding used to decode the stream's bytes into
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000578 strings, and to encode strings into bytes.
579
580 .. attribute:: newlines
581
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000582 A string, a tuple of strings, or ``None``, indicating the newlines
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000583 translated so far.
584
585 .. method:: read(n)
586
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000587 Read and return at most *n* characters from the stream as a single
588 :class:`str`. If *n* is negative or ``None``, reads to EOF.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000589
590 .. method:: readline()
591
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000592 Read until newline or EOF and return a single ``str``. If the stream is
593 already at EOF, an empty string is returned.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000594
595 .. method:: write(s)
596
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000597 Write the string *s* to the stream and return the number of characters
598 written.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000599
600
601.. class:: TextIOWrapper(buffer[, encoding[, errors[, newline[, line_buffering]]]])
602
603 A buffered text stream over a :class:`BufferedIOBase` raw stream, *buffer*.
604 It inherits :class:`TextIOBase`.
605
606 *encoding* gives the name of the encoding that the stream will be decoded or
607 encoded with. It defaults to :func:`locale.getpreferredencoding`.
608
Benjamin Peterson53be57e2008-04-19 19:34:05 +0000609 *errors* is an optional string that specifies how encoding and decoding
610 errors are to be handled. Pass ``'strict'`` to raise a :exc:`ValueError`
611 exception if there is an encoding error (the default of ``None`` has the same
612 effect), or pass ``'ignore'`` to ignore errors. (Note that ignoring encoding
613 errors can lead to data loss.) ``'replace'`` causes a replacement marker
Benjamin Petersona7d09032008-04-19 19:47:34 +0000614 (such as ``'?'``) to be inserted where there is malformed data. When
615 writing, ``'xmlcharrefreplace'`` (replace with the appropriate XML character
616 reference) or ``'backslashreplace'`` (replace with backslashed escape
617 sequences) can be used. Any other error handling name that has been
618 registered with :func:`codecs.register_error` is also valid.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000619
620 *newline* can be ``None``, ``''``, ``'\n'``, ``'\r'``, or ``'\r\n'``. It
621 controls the handling of line endings. If it is ``None``, universal newlines
622 is enabled. With this enabled, on input, the lines endings ``'\n'``,
623 ``'\r'``, or ``'\r\n'`` are translated to ``'\n'`` before being returned to
624 the caller. Conversely, on output, ``'\n'`` is translated to the system
Jesus Cea585ad8a2009-07-02 15:37:21 +0000625 default line separator, :data:`os.linesep`. If *newline* is any other of its
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000626 legal values, that newline becomes the newline when the file is read and it
627 is returned untranslated. On output, ``'\n'`` is converted to the *newline*.
628
629 If *line_buffering* is ``True``, :meth:`flush` is implied when a call to
630 write contains a newline character.
631
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000632 :class:`TextIOWrapper` provides these data attributes in addition to those of
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000633 :class:`TextIOBase` and its parents:
634
635 .. attribute:: errors
636
637 The encoding and decoding error setting.
638
639 .. attribute:: line_buffering
640
641 Whether line buffering is enabled.
Georg Brandl734373c2009-01-03 21:55:17 +0000642
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000643
644.. class:: StringIO([initial_value[, encoding[, errors[, newline]]]])
645
Georg Brandl58ed9282009-10-27 13:38:33 +0000646 An in-memory stream for text. It inherits :class:`TextIOWrapper`.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000647
648 Create a new StringIO stream with an inital value, encoding, error handling,
649 and newline setting. See :class:`TextIOWrapper`\'s constructor for more
650 information.
651
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000652 :class:`StringIO` provides this method in addition to those from
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000653 :class:`TextIOWrapper` and its parents:
654
655 .. method:: getvalue()
656
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000657 Return a ``str`` containing the entire contents of the buffer.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000658
659
660.. class:: IncrementalNewlineDecoder
661
662 A helper codec that decodes newlines for universal newlines mode. It
663 inherits :class:`codecs.IncrementalDecoder`.
664