blob: 1a4b959ebf4b01a51d79ccd8a56d45f3bfcfb23e [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
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000297 Truncate the file to at most *size* bytes. *size* defaults to the current
Antoine Pitrouf34c4c62010-04-28 19:59:22 +0000298 file position, as returned by :meth:`tell`. Note that the current file
299 position isn't changed; if you want to change it to the new end of
300 file, you have to :meth:`seek()` explicitly.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000301
302 .. method:: writable()
303
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000304 Return ``True`` if the stream supports writing. If ``False``,
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000305 :meth:`write` and :meth:`truncate` will raise :exc:`IOError`.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000306
307 .. method:: writelines(lines)
308
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000309 Write a list of lines to the stream. Line separators are not added, so it
310 is usual for each of the lines provided to have a line separator at the
311 end.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000312
313
314.. class:: RawIOBase
315
316 Base class for raw binary I/O. It inherits :class:`IOBase`. There is no
317 public constructor.
318
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000319 In addition to the attributes and methods from :class:`IOBase`,
320 RawIOBase provides the following methods:
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000321
322 .. method:: read([n])
323
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000324 Read and return all the bytes from the stream until EOF, or if *n* is
325 specified, up to *n* bytes. Only one system call is ever made. An empty
326 bytes object is returned on EOF; ``None`` is returned if the object is set
327 not to block and has no data to read.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000328
329 .. method:: readall()
330
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000331 Read and return all the bytes from the stream until EOF, using multiple
332 calls to the stream if necessary.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000333
334 .. method:: readinto(b)
335
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000336 Read up to len(b) bytes into bytearray *b* and return the number of bytes
337 read.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000338
339 .. method:: write(b)
340
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000341 Write the given bytes or bytearray object, *b*, to the underlying raw
342 stream and return the number of bytes written (This is never less than
343 ``len(b)``, since if the write fails, an :exc:`IOError` will be raised).
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000344
345
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000346.. class:: BufferedIOBase
347
348 Base class for streams that support buffering. It inherits :class:`IOBase`.
349 There is no public constructor.
350
351 The main difference with :class:`RawIOBase` is that the :meth:`read` method
352 supports omitting the *size* argument, and does not have a default
353 implementation that defers to :meth:`readinto`.
354
355 In addition, :meth:`read`, :meth:`readinto`, and :meth:`write` may raise
356 :exc:`BlockingIOError` if the underlying raw stream is in non-blocking mode
357 and not ready; unlike their raw counterparts, they will never return
358 ``None``.
359
360 A typical implementation should not inherit from a :class:`RawIOBase`
361 implementation, but wrap one like :class:`BufferedWriter` and
362 :class:`BufferedReader`.
363
364 :class:`BufferedIOBase` provides or overrides these methods in addition to
365 those from :class:`IOBase`:
366
367 .. method:: read([n])
368
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000369 Read and return up to *n* bytes. If the argument is omitted, ``None``, or
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000370 negative, data is read and returned until EOF is reached. An empty bytes
371 object is returned if the stream is already at EOF.
372
373 If the argument is positive, and the underlying raw stream is not
374 interactive, multiple raw reads may be issued to satisfy the byte count
375 (unless EOF is reached first). But for interactive raw streams, at most
376 one raw read will be issued, and a short result does not imply that EOF is
377 imminent.
378
379 A :exc:`BlockingIOError` is raised if the underlying raw stream has no
380 data at the moment.
381
382 .. method:: readinto(b)
383
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000384 Read up to len(b) bytes into bytearray *b* and return the number of bytes
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000385 read.
386
387 Like :meth:`read`, multiple reads may be issued to the underlying raw
388 stream, unless the latter is 'interactive.'
389
390 A :exc:`BlockingIOError` is raised if the underlying raw stream has no
391 data at the moment.
392
393 .. method:: write(b)
394
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000395 Write the given bytes or bytearray object, *b*, to the underlying raw
396 stream and return the number of bytes written (never less than ``len(b)``,
397 since if the write fails an :exc:`IOError` will be raised).
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000398
399 A :exc:`BlockingIOError` is raised if the buffer is full, and the
400 underlying raw stream cannot accept more data at the moment.
401
402
Georg Brandl4f8084e2009-10-27 13:20:10 +0000403Raw File I/O
404------------
405
406.. class:: FileIO(name[, mode])
407
408 :class:`FileIO` represents a file containing bytes data. It implements
409 the :class:`RawIOBase` interface (and therefore the :class:`IOBase`
410 interface, too).
411
412 The *mode* can be ``'r'``, ``'w'`` or ``'a'`` for reading (default), writing,
413 or appending. The file will be created if it doesn't exist when opened for
414 writing or appending; it will be truncated when opened for writing. Add a
415 ``'+'`` to the mode to allow simultaneous reading and writing.
416
417 In addition to the attributes and methods from :class:`IOBase` and
418 :class:`RawIOBase`, :class:`FileIO` provides the following data
419 attributes and methods:
420
421 .. attribute:: mode
422
423 The mode as given in the constructor.
424
425 .. attribute:: name
426
427 The file name. This is the file descriptor of the file when no name is
428 given in the constructor.
429
430 .. method:: read([n])
431
432 Read and return at most *n* bytes. Only one system call is made, so it is
433 possible that less data than was requested is returned. Use :func:`len`
434 on the returned bytes object to see how many bytes were actually returned.
435 (In non-blocking mode, ``None`` is returned when no data is available.)
436
437 .. method:: readall()
438
439 Read and return the entire file's contents in a single bytes object. As
440 much as immediately available is returned in non-blocking mode. If the
441 EOF has been reached, ``b''`` is returned.
442
443 .. method:: write(b)
444
445 Write the bytes or bytearray object, *b*, to the file, and return
446 the number actually written. Only one system call is made, so it
447 is possible that only some of the data is written.
448
449 Note that the inherited ``readinto()`` method should not be used on
450 :class:`FileIO` objects.
451
452
453Buffered Streams
454----------------
455
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000456.. class:: BytesIO([initial_bytes])
457
458 A stream implementation using an in-memory bytes buffer. It inherits
459 :class:`BufferedIOBase`.
460
461 The argument *initial_bytes* is an optional initial bytearray.
462
463 :class:`BytesIO` provides or overrides these methods in addition to those
464 from :class:`BufferedIOBase` and :class:`IOBase`:
465
466 .. method:: getvalue()
467
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000468 Return ``bytes`` containing the entire contents of the buffer.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000469
470 .. method:: read1()
471
Benjamin Peterson53be57e2008-04-19 19:34:05 +0000472 In :class:`BytesIO`, this is the same as :meth:`read`.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000473
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000474
475.. class:: BufferedReader(raw[, buffer_size])
476
Benjamin Peterson53be57e2008-04-19 19:34:05 +0000477 A buffer for a readable, sequential :class:`RawIOBase` object. It inherits
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000478 :class:`BufferedIOBase`.
479
480 The constructor creates a :class:`BufferedReader` for the given readable
481 *raw* stream and *buffer_size*. If *buffer_size* is omitted,
482 :data:`DEFAULT_BUFFER_SIZE` is used.
483
484 :class:`BufferedReader` provides or overrides these methods in addition to
485 those from :class:`BufferedIOBase` and :class:`IOBase`:
486
487 .. method:: peek([n])
488
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000489 Return 1 (or *n* if specified) bytes from a buffer without advancing the
490 position. Only a single read on the raw stream is done to satisfy the
491 call. The number of bytes returned may be less than requested since at
492 most all the buffer's bytes from the current position to the end are
493 returned.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000494
495 .. method:: read([n])
496
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000497 Read and return *n* bytes, or if *n* is not given or negative, until EOF
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000498 or if the read call would block in non-blocking mode.
499
500 .. method:: read1(n)
501
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000502 Read and return up to *n* bytes with only one call on the raw stream. If
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000503 at least one byte is buffered, only buffered bytes are returned.
504 Otherwise, one raw stream read call is made.
505
506
507.. class:: BufferedWriter(raw[, buffer_size[, max_buffer_size]])
508
509 A buffer for a writeable sequential RawIO object. It inherits
510 :class:`BufferedIOBase`.
511
512 The constructor creates a :class:`BufferedWriter` for the given writeable
513 *raw* stream. If the *buffer_size* is not given, it defaults to
514 :data:`DEAFULT_BUFFER_SIZE`. If *max_buffer_size* is omitted, it defaults to
515 twice the buffer size.
516
517 :class:`BufferedWriter` provides or overrides these methods in addition to
518 those from :class:`BufferedIOBase` and :class:`IOBase`:
519
520 .. method:: flush()
521
522 Force bytes held in the buffer into the raw stream. A
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000523 :exc:`BlockingIOError` should be raised if the raw stream blocks.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000524
525 .. method:: write(b)
526
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000527 Write the bytes or bytearray object, *b*, onto the raw stream and return
528 the number of bytes written. A :exc:`BlockingIOError` is raised when the
529 raw stream blocks.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000530
531
532.. class:: BufferedRWPair(reader, writer[, buffer_size[, max_buffer_size]])
533
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000534 A combined buffered writer and reader object for a raw stream that can be
535 written to and read from. It has and supports both :meth:`read`, :meth:`write`,
536 and their variants. This is useful for sockets and two-way pipes.
537 It inherits :class:`BufferedIOBase`.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000538
539 *reader* and *writer* are :class:`RawIOBase` objects that are readable and
540 writeable respectively. If the *buffer_size* is omitted it defaults to
541 :data:`DEFAULT_BUFFER_SIZE`. The *max_buffer_size* (for the buffered writer)
542 defaults to twice the buffer size.
543
544 :class:`BufferedRWPair` implements all of :class:`BufferedIOBase`\'s methods.
545
546
547.. class:: BufferedRandom(raw[, buffer_size[, max_buffer_size]])
548
549 A buffered interface to random access streams. It inherits
550 :class:`BufferedReader` and :class:`BufferedWriter`.
551
552 The constructor creates a reader and writer for a seekable raw stream, given
553 in the first argument. If the *buffer_size* is omitted it defaults to
554 :data:`DEFAULT_BUFFER_SIZE`. The *max_buffer_size* (for the buffered writer)
555 defaults to twice the buffer size.
556
557 :class:`BufferedRandom` is capable of anything :class:`BufferedReader` or
558 :class:`BufferedWriter` can do.
559
560
561Text I/O
562--------
563
564.. class:: TextIOBase
565
566 Base class for text streams. This class provides a character and line based
567 interface to stream I/O. There is no :meth:`readinto` method because
568 Python's character strings are immutable. It inherits :class:`IOBase`.
569 There is no public constructor.
570
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000571 :class:`TextIOBase` provides or overrides these data attributes and
572 methods in addition to those from :class:`IOBase`:
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000573
574 .. attribute:: encoding
575
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000576 The name of the encoding used to decode the stream's bytes into
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000577 strings, and to encode strings into bytes.
578
579 .. attribute:: newlines
580
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000581 A string, a tuple of strings, or ``None``, indicating the newlines
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000582 translated so far.
583
584 .. method:: read(n)
585
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000586 Read and return at most *n* characters from the stream as a single
587 :class:`str`. If *n* is negative or ``None``, reads to EOF.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000588
589 .. method:: readline()
590
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000591 Read until newline or EOF and return a single ``str``. If the stream is
592 already at EOF, an empty string is returned.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000593
594 .. method:: write(s)
595
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000596 Write the string *s* to the stream and return the number of characters
597 written.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000598
599
600.. class:: TextIOWrapper(buffer[, encoding[, errors[, newline[, line_buffering]]]])
601
602 A buffered text stream over a :class:`BufferedIOBase` raw stream, *buffer*.
603 It inherits :class:`TextIOBase`.
604
605 *encoding* gives the name of the encoding that the stream will be decoded or
606 encoded with. It defaults to :func:`locale.getpreferredencoding`.
607
Benjamin Peterson53be57e2008-04-19 19:34:05 +0000608 *errors* is an optional string that specifies how encoding and decoding
609 errors are to be handled. Pass ``'strict'`` to raise a :exc:`ValueError`
610 exception if there is an encoding error (the default of ``None`` has the same
611 effect), or pass ``'ignore'`` to ignore errors. (Note that ignoring encoding
612 errors can lead to data loss.) ``'replace'`` causes a replacement marker
Benjamin Petersona7d09032008-04-19 19:47:34 +0000613 (such as ``'?'``) to be inserted where there is malformed data. When
614 writing, ``'xmlcharrefreplace'`` (replace with the appropriate XML character
615 reference) or ``'backslashreplace'`` (replace with backslashed escape
616 sequences) can be used. Any other error handling name that has been
617 registered with :func:`codecs.register_error` is also valid.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000618
619 *newline* can be ``None``, ``''``, ``'\n'``, ``'\r'``, or ``'\r\n'``. It
620 controls the handling of line endings. If it is ``None``, universal newlines
621 is enabled. With this enabled, on input, the lines endings ``'\n'``,
622 ``'\r'``, or ``'\r\n'`` are translated to ``'\n'`` before being returned to
623 the caller. Conversely, on output, ``'\n'`` is translated to the system
Jesus Cea585ad8a2009-07-02 15:37:21 +0000624 default line separator, :data:`os.linesep`. If *newline* is any other of its
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000625 legal values, that newline becomes the newline when the file is read and it
626 is returned untranslated. On output, ``'\n'`` is converted to the *newline*.
627
628 If *line_buffering* is ``True``, :meth:`flush` is implied when a call to
629 write contains a newline character.
630
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000631 :class:`TextIOWrapper` provides these data attributes in addition to those of
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000632 :class:`TextIOBase` and its parents:
633
634 .. attribute:: errors
635
636 The encoding and decoding error setting.
637
638 .. attribute:: line_buffering
639
640 Whether line buffering is enabled.
Georg Brandl734373c2009-01-03 21:55:17 +0000641
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000642
643.. class:: StringIO([initial_value[, encoding[, errors[, newline]]]])
644
Georg Brandl58ed9282009-10-27 13:38:33 +0000645 An in-memory stream for text. It inherits :class:`TextIOWrapper`.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000646
647 Create a new StringIO stream with an inital value, encoding, error handling,
648 and newline setting. See :class:`TextIOWrapper`\'s constructor for more
649 information.
650
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000651 :class:`StringIO` provides this method in addition to those from
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000652 :class:`TextIOWrapper` and its parents:
653
654 .. method:: getvalue()
655
Benjamin Peterson3c399d12008-04-22 02:16:03 +0000656 Return a ``str`` containing the entire contents of the buffer.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000657
658
659.. class:: IncrementalNewlineDecoder
660
661 A helper codec that decodes newlines for universal newlines mode. It
662 inherits :class:`codecs.IncrementalDecoder`.
663