blob: e3f8b36a09e6e25a970f3d1df0533241c54cf896 [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
Antoine Pitrouf34c4c62010-04-28 19:59:22 +0000229 (e.g. reading or writing) will raise an :exc:`ValueError`.
230
231 As a convenience, it is allowed to call this method more than once;
232 only the first call, however, will have an effect.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000233
234 .. attribute:: closed
235
236 True if the stream is closed.
237
238 .. method:: fileno()
239
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000240 Return the underlying file descriptor (an integer) of the stream if it
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000241 exists. An :exc:`IOError` is raised if the IO object does not use a file
242 descriptor.
243
244 .. method:: flush()
245
Benjamin Peterson53be57e2008-04-19 19:34:05 +0000246 Flush the write buffers of the stream if applicable. This does nothing
247 for read-only and non-blocking streams.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000248
249 .. method:: isatty()
250
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000251 Return ``True`` if the stream is interactive (i.e., connected to
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000252 a terminal/tty device).
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000253
254 .. method:: readable()
255
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000256 Return ``True`` if the stream can be read from. If False, :meth:`read`
257 will raise :exc:`IOError`.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000258
259 .. method:: readline([limit])
260
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000261 Read and return one line from the stream. If *limit* is specified, at
262 most *limit* bytes will be read.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000263
264 The line terminator is always ``b'\n'`` for binary files; for text files,
Georg Brandl0dfdf002009-10-27 14:36:50 +0000265 the *newlines* argument to :func:`.open` can be used to select the line
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000266 terminator(s) recognized.
267
268 .. method:: readlines([hint])
269
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000270 Read and return a list of lines from the stream. *hint* can be specified
271 to control the number of lines read: no more lines will be read if the
272 total size (in bytes/characters) of all lines so far exceeds *hint*.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000273
274 .. method:: seek(offset[, whence])
275
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000276 Change the stream position to the given byte *offset*. *offset* is
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000277 interpreted relative to the position indicated by *whence*. Values for
278 *whence* are:
279
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000280 * ``0`` -- start of the stream (the default); *offset* should be zero or positive
281 * ``1`` -- current stream position; *offset* may be negative
282 * ``2`` -- end of the stream; *offset* is usually negative
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000283
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000284 Return the new absolute position.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000285
286 .. method:: seekable()
287
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000288 Return ``True`` if the stream supports random access. If ``False``,
289 :meth:`seek`, :meth:`tell` and :meth:`truncate` will raise :exc:`IOError`.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000290
291 .. method:: tell()
292
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000293 Return the current stream position.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000294
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000295 .. method:: truncate([size])
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000296
Antoine Pitrouae15f172010-05-29 12:08:31 +0000297 Resize the stream to the given *size* in bytes (or the current position
298 if *size* is not specified). The current stream position isn't changed.
299 This resizing can extend or reduce the current file size. In case of
300 extension, the contents of the new file area depend on the platform
301 (on most systems, additional bytes are zero-filled, on Windows they're
302 undetermined). The new file size is returned.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000303
304 .. method:: writable()
305
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000306 Return ``True`` if the stream supports writing. If ``False``,
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000307 :meth:`write` and :meth:`truncate` will raise :exc:`IOError`.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000308
309 .. method:: writelines(lines)
310
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000311 Write a list of lines to the stream. Line separators are not added, so it
312 is usual for each of the lines provided to have a line separator at the
313 end.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000314
315
316.. class:: RawIOBase
317
318 Base class for raw binary I/O. It inherits :class:`IOBase`. There is no
319 public constructor.
320
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000321 In addition to the attributes and methods from :class:`IOBase`,
322 RawIOBase provides the following methods:
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000323
324 .. method:: read([n])
325
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000326 Read and return all the bytes from the stream until EOF, or if *n* is
327 specified, up to *n* bytes. Only one system call is ever made. An empty
328 bytes object is returned on EOF; ``None`` is returned if the object is set
329 not to block and has no data to read.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000330
331 .. method:: readall()
332
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000333 Read and return all the bytes from the stream until EOF, using multiple
334 calls to the stream if necessary.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000335
336 .. method:: readinto(b)
337
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000338 Read up to len(b) bytes into bytearray *b* and return the number of bytes
339 read.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000340
341 .. method:: write(b)
342
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000343 Write the given bytes or bytearray object, *b*, to the underlying raw
344 stream and return the number of bytes written (This is never less than
345 ``len(b)``, since if the write fails, an :exc:`IOError` will be raised).
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000346
347
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000348.. class:: BufferedIOBase
349
350 Base class for streams that support buffering. It inherits :class:`IOBase`.
351 There is no public constructor.
352
353 The main difference with :class:`RawIOBase` is that the :meth:`read` method
354 supports omitting the *size* argument, and does not have a default
355 implementation that defers to :meth:`readinto`.
356
357 In addition, :meth:`read`, :meth:`readinto`, and :meth:`write` may raise
358 :exc:`BlockingIOError` if the underlying raw stream is in non-blocking mode
359 and not ready; unlike their raw counterparts, they will never return
360 ``None``.
361
362 A typical implementation should not inherit from a :class:`RawIOBase`
363 implementation, but wrap one like :class:`BufferedWriter` and
364 :class:`BufferedReader`.
365
366 :class:`BufferedIOBase` provides or overrides these methods in addition to
367 those from :class:`IOBase`:
368
369 .. method:: read([n])
370
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000371 Read and return up to *n* bytes. If the argument is omitted, ``None``, or
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000372 negative, data is read and returned until EOF is reached. An empty bytes
373 object is returned if the stream is already at EOF.
374
375 If the argument is positive, and the underlying raw stream is not
376 interactive, multiple raw reads may be issued to satisfy the byte count
377 (unless EOF is reached first). But for interactive raw streams, at most
378 one raw read will be issued, and a short result does not imply that EOF is
379 imminent.
380
381 A :exc:`BlockingIOError` is raised if the underlying raw stream has no
382 data at the moment.
383
384 .. method:: readinto(b)
385
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000386 Read up to len(b) bytes into bytearray *b* and return the number of bytes
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000387 read.
388
389 Like :meth:`read`, multiple reads may be issued to the underlying raw
390 stream, unless the latter is 'interactive.'
391
392 A :exc:`BlockingIOError` is raised if the underlying raw stream has no
393 data at the moment.
394
395 .. method:: write(b)
396
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000397 Write the given bytes or bytearray object, *b*, to the underlying raw
398 stream and return the number of bytes written (never less than ``len(b)``,
399 since if the write fails an :exc:`IOError` will be raised).
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000400
401 A :exc:`BlockingIOError` is raised if the buffer is full, and the
402 underlying raw stream cannot accept more data at the moment.
403
404
Georg Brandl4f8084e2009-10-27 13:20:10 +0000405Raw File I/O
406------------
407
408.. class:: FileIO(name[, mode])
409
410 :class:`FileIO` represents a file containing bytes data. It implements
411 the :class:`RawIOBase` interface (and therefore the :class:`IOBase`
412 interface, too).
413
414 The *mode* can be ``'r'``, ``'w'`` or ``'a'`` for reading (default), writing,
415 or appending. The file will be created if it doesn't exist when opened for
416 writing or appending; it will be truncated when opened for writing. Add a
417 ``'+'`` to the mode to allow simultaneous reading and writing.
418
419 In addition to the attributes and methods from :class:`IOBase` and
420 :class:`RawIOBase`, :class:`FileIO` provides the following data
421 attributes and methods:
422
423 .. attribute:: mode
424
425 The mode as given in the constructor.
426
427 .. attribute:: name
428
429 The file name. This is the file descriptor of the file when no name is
430 given in the constructor.
431
432 .. method:: read([n])
433
434 Read and return at most *n* bytes. Only one system call is made, so it is
435 possible that less data than was requested is returned. Use :func:`len`
436 on the returned bytes object to see how many bytes were actually returned.
437 (In non-blocking mode, ``None`` is returned when no data is available.)
438
439 .. method:: readall()
440
441 Read and return the entire file's contents in a single bytes object. As
442 much as immediately available is returned in non-blocking mode. If the
443 EOF has been reached, ``b''`` is returned.
444
445 .. method:: write(b)
446
447 Write the bytes or bytearray object, *b*, to the file, and return
448 the number actually written. Only one system call is made, so it
449 is possible that only some of the data is written.
450
451 Note that the inherited ``readinto()`` method should not be used on
452 :class:`FileIO` objects.
453
454
455Buffered Streams
456----------------
457
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000458.. class:: BytesIO([initial_bytes])
459
460 A stream implementation using an in-memory bytes buffer. It inherits
461 :class:`BufferedIOBase`.
462
463 The argument *initial_bytes* is an optional initial bytearray.
464
465 :class:`BytesIO` provides or overrides these methods in addition to those
466 from :class:`BufferedIOBase` and :class:`IOBase`:
467
468 .. method:: getvalue()
469
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000470 Return ``bytes`` containing the entire contents of the buffer.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000471
472 .. method:: read1()
473
Benjamin Peterson53be57e2008-04-19 19:34:05 +0000474 In :class:`BytesIO`, this is the same as :meth:`read`.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000475
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000476
477.. class:: BufferedReader(raw[, buffer_size])
478
Benjamin Peterson53be57e2008-04-19 19:34:05 +0000479 A buffer for a readable, sequential :class:`RawIOBase` object. It inherits
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000480 :class:`BufferedIOBase`.
481
482 The constructor creates a :class:`BufferedReader` for the given readable
483 *raw* stream and *buffer_size*. If *buffer_size* is omitted,
484 :data:`DEFAULT_BUFFER_SIZE` is used.
485
486 :class:`BufferedReader` provides or overrides these methods in addition to
487 those from :class:`BufferedIOBase` and :class:`IOBase`:
488
489 .. method:: peek([n])
490
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000491 Return 1 (or *n* if specified) bytes from a buffer without advancing the
492 position. Only a single read on the raw stream is done to satisfy the
493 call. The number of bytes returned may be less than requested since at
494 most all the buffer's bytes from the current position to the end are
495 returned.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000496
497 .. method:: read([n])
498
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000499 Read and return *n* bytes, or if *n* is not given or negative, until EOF
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000500 or if the read call would block in non-blocking mode.
501
502 .. method:: read1(n)
503
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000504 Read and return up to *n* bytes with only one call on the raw stream. If
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000505 at least one byte is buffered, only buffered bytes are returned.
506 Otherwise, one raw stream read call is made.
507
508
509.. class:: BufferedWriter(raw[, buffer_size[, max_buffer_size]])
510
511 A buffer for a writeable sequential RawIO object. It inherits
512 :class:`BufferedIOBase`.
513
514 The constructor creates a :class:`BufferedWriter` for the given writeable
515 *raw* stream. If the *buffer_size* is not given, it defaults to
516 :data:`DEAFULT_BUFFER_SIZE`. If *max_buffer_size* is omitted, it defaults to
517 twice the buffer size.
518
519 :class:`BufferedWriter` provides or overrides these methods in addition to
520 those from :class:`BufferedIOBase` and :class:`IOBase`:
521
522 .. method:: flush()
523
524 Force bytes held in the buffer into the raw stream. A
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000525 :exc:`BlockingIOError` should be raised if the raw stream blocks.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000526
527 .. method:: write(b)
528
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000529 Write the bytes or bytearray object, *b*, onto the raw stream and return
530 the number of bytes written. A :exc:`BlockingIOError` is raised when the
531 raw stream blocks.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000532
533
534.. class:: BufferedRWPair(reader, writer[, buffer_size[, max_buffer_size]])
535
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000536 A combined buffered writer and reader object for a raw stream that can be
537 written to and read from. It has and supports both :meth:`read`, :meth:`write`,
538 and their variants. This is useful for sockets and two-way pipes.
539 It inherits :class:`BufferedIOBase`.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000540
541 *reader* and *writer* are :class:`RawIOBase` objects that are readable and
542 writeable respectively. If the *buffer_size* is omitted it defaults to
543 :data:`DEFAULT_BUFFER_SIZE`. The *max_buffer_size* (for the buffered writer)
544 defaults to twice the buffer size.
545
546 :class:`BufferedRWPair` implements all of :class:`BufferedIOBase`\'s methods.
547
548
549.. class:: BufferedRandom(raw[, buffer_size[, max_buffer_size]])
550
551 A buffered interface to random access streams. It inherits
552 :class:`BufferedReader` and :class:`BufferedWriter`.
553
554 The constructor creates a reader and writer for a seekable raw stream, given
555 in the first argument. If the *buffer_size* is omitted it defaults to
556 :data:`DEFAULT_BUFFER_SIZE`. The *max_buffer_size* (for the buffered writer)
557 defaults to twice the buffer size.
558
559 :class:`BufferedRandom` is capable of anything :class:`BufferedReader` or
560 :class:`BufferedWriter` can do.
561
562
563Text I/O
564--------
565
566.. class:: TextIOBase
567
568 Base class for text streams. This class provides a character and line based
569 interface to stream I/O. There is no :meth:`readinto` method because
570 Python's character strings are immutable. It inherits :class:`IOBase`.
571 There is no public constructor.
572
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000573 :class:`TextIOBase` provides or overrides these data attributes and
574 methods in addition to those from :class:`IOBase`:
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000575
576 .. attribute:: encoding
577
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000578 The name of the encoding used to decode the stream's bytes into
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000579 strings, and to encode strings into bytes.
580
581 .. attribute:: newlines
582
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000583 A string, a tuple of strings, or ``None``, indicating the newlines
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000584 translated so far.
585
586 .. method:: read(n)
587
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000588 Read and return at most *n* characters from the stream as a single
589 :class:`str`. If *n* is negative or ``None``, reads to EOF.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000590
591 .. method:: readline()
592
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000593 Read until newline or EOF and return a single ``str``. If the stream is
594 already at EOF, an empty string is returned.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000595
596 .. method:: write(s)
597
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000598 Write the string *s* to the stream and return the number of characters
599 written.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000600
601
602.. class:: TextIOWrapper(buffer[, encoding[, errors[, newline[, line_buffering]]]])
603
604 A buffered text stream over a :class:`BufferedIOBase` raw stream, *buffer*.
605 It inherits :class:`TextIOBase`.
606
607 *encoding* gives the name of the encoding that the stream will be decoded or
608 encoded with. It defaults to :func:`locale.getpreferredencoding`.
609
Benjamin Peterson53be57e2008-04-19 19:34:05 +0000610 *errors* is an optional string that specifies how encoding and decoding
611 errors are to be handled. Pass ``'strict'`` to raise a :exc:`ValueError`
612 exception if there is an encoding error (the default of ``None`` has the same
613 effect), or pass ``'ignore'`` to ignore errors. (Note that ignoring encoding
614 errors can lead to data loss.) ``'replace'`` causes a replacement marker
Benjamin Petersona7d09032008-04-19 19:47:34 +0000615 (such as ``'?'``) to be inserted where there is malformed data. When
616 writing, ``'xmlcharrefreplace'`` (replace with the appropriate XML character
617 reference) or ``'backslashreplace'`` (replace with backslashed escape
618 sequences) can be used. Any other error handling name that has been
619 registered with :func:`codecs.register_error` is also valid.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000620
621 *newline* can be ``None``, ``''``, ``'\n'``, ``'\r'``, or ``'\r\n'``. It
622 controls the handling of line endings. If it is ``None``, universal newlines
623 is enabled. With this enabled, on input, the lines endings ``'\n'``,
624 ``'\r'``, or ``'\r\n'`` are translated to ``'\n'`` before being returned to
625 the caller. Conversely, on output, ``'\n'`` is translated to the system
Jesus Cea585ad8a2009-07-02 15:37:21 +0000626 default line separator, :data:`os.linesep`. If *newline* is any other of its
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000627 legal values, that newline becomes the newline when the file is read and it
628 is returned untranslated. On output, ``'\n'`` is converted to the *newline*.
629
630 If *line_buffering* is ``True``, :meth:`flush` is implied when a call to
631 write contains a newline character.
632
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000633 :class:`TextIOWrapper` provides these data attributes in addition to those of
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000634 :class:`TextIOBase` and its parents:
635
636 .. attribute:: errors
637
638 The encoding and decoding error setting.
639
640 .. attribute:: line_buffering
641
642 Whether line buffering is enabled.
Georg Brandl734373c2009-01-03 21:55:17 +0000643
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000644
645.. class:: StringIO([initial_value[, encoding[, errors[, newline]]]])
646
Georg Brandl58ed9282009-10-27 13:38:33 +0000647 An in-memory stream for text. It inherits :class:`TextIOWrapper`.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000648
649 Create a new StringIO stream with an inital value, encoding, error handling,
650 and newline setting. See :class:`TextIOWrapper`\'s constructor for more
651 information.
652
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000653 :class:`StringIO` provides this method in addition to those from
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000654 :class:`TextIOWrapper` and its parents:
655
656 .. method:: getvalue()
657
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000658 Return a ``str`` containing the entire contents of the buffer.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000659
660
661.. class:: IncrementalNewlineDecoder
662
663 A helper codec that decodes newlines for universal newlines mode. It
664 inherits :class:`codecs.IncrementalDecoder`.
665