blob: df0e7e949825c29fad6e4507bf6e1281812a9c55 [file] [log] [blame]
Georg Brandl014197c2008-04-09 18:40:51 +00001:mod:`io` --- Core tools for working with streams
2=================================================
3
4.. module:: io
5 :synopsis: Core tools for working with streams.
6.. moduleauthor:: Guido van Rossum <guido@python.org>
7.. moduleauthor:: Mike Verdone <mike.verdone@gmail.com>
8.. moduleauthor:: Mark Russell <mark.russell@zen.co.uk>
Benjamin Peterson058e31e2009-01-16 03:54:08 +00009.. sectionauthor:: Benjamin Peterson <benjamin@python.org>
Georg Brandl014197c2008-04-09 18:40:51 +000010
11The :mod:`io` module provides the Python interfaces to stream handling. The
12builtin :func:`open` function is defined in this module.
13
14At the top of the I/O hierarchy is the abstract base class :class:`IOBase`. It
15defines the basic interface to a stream. Note, however, that there is no
16seperation between reading and writing to streams; implementations are allowed
17to throw an :exc:`IOError` if they do not support a given operation.
18
19Extending :class:`IOBase` is :class:`RawIOBase` which deals simply with the
20reading and writing of raw bytes to a stream. :class:`FileIO` subclasses
Mark Summerfielde6d5f302008-04-21 10:29:45 +000021:class:`RawIOBase` to provide an interface to files in the machine's
22file system.
Georg Brandl014197c2008-04-09 18:40:51 +000023
24:class:`BufferedIOBase` deals with buffering on a raw byte stream
25(:class:`RawIOBase`). Its subclasses, :class:`BufferedWriter`,
26:class:`BufferedReader`, and :class:`BufferedRWPair` buffer streams that are
Mark Summerfielde6d5f302008-04-21 10:29:45 +000027readable, writable, and both readable and writable.
28:class:`BufferedRandom` provides a buffered interface to random access
29streams. :class:`BytesIO` is a simple stream of in-memory bytes.
Georg Brandl014197c2008-04-09 18:40:51 +000030
Mark Summerfielde6d5f302008-04-21 10:29:45 +000031Another :class:`IOBase` subclass, :class:`TextIOBase`, deals with
32streams whose bytes represent text, and handles encoding and decoding
33from and to strings. :class:`TextIOWrapper`, which extends it, is a
34buffered text interface to a buffered raw stream
35(:class:`BufferedIOBase`). Finally, :class:`StringIO` is an in-memory
36stream for text.
Georg Brandl014197c2008-04-09 18:40:51 +000037
Benjamin Peterson2c5f8282008-04-13 00:27:46 +000038Argument names are not part of the specification, and only the arguments of
Benjamin Petersonb85a5842008-04-13 21:39:58 +000039:func:`open` are intended to be used as keyword arguments.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +000040
Georg Brandl014197c2008-04-09 18:40:51 +000041
42Module Interface
43----------------
44
45.. data:: DEFAULT_BUFFER_SIZE
46
47 An int containing the default buffer size used by the module's buffered I/O
Benjamin Petersonb85a5842008-04-13 21:39:58 +000048 classes. :func:`open` uses the file's blksize (as obtained by
Benjamin Peterson2c5f8282008-04-13 00:27:46 +000049 :func:`os.stat`) if possible.
Georg Brandl014197c2008-04-09 18:40:51 +000050
51.. function:: open(file[, mode[, buffering[, encoding[, errors[, newline[, closefd=True]]]]]])
52
Benjamin Petersondd219122008-04-11 21:17:32 +000053 Open *file* and return a stream. If the file cannot be opened, an
54 :exc:`IOError` is raised.
Georg Brandl014197c2008-04-09 18:40:51 +000055
Benjamin Petersondd219122008-04-11 21:17:32 +000056 *file* is either a string giving the name (and the path if the file isn't in
Mark Summerfielde6d5f302008-04-21 10:29:45 +000057 the current working directory) of the file to be opened or a file
58 descriptor of the file to be opened. (If a file descriptor is given,
59 for example, from :func:`os.fdopen`, it is closed when the returned
60 I/O object is closed, unless *closefd* is set to ``False``.)
Georg Brandl014197c2008-04-09 18:40:51 +000061
Benjamin Petersondd219122008-04-11 21:17:32 +000062 *mode* is an optional string that specifies the mode in which the file is
63 opened. It defaults to ``'r'`` which means open for reading in text mode.
64 Other common values are ``'w'`` for writing (truncating the file if it
65 already exists), and ``'a'`` for appending (which on *some* Unix systems,
66 means that *all* writes append to the end of the file regardless of the
67 current seek position). In text mode, if *encoding* is not specified the
68 encoding used is platform dependent. (For reading and writing raw bytes use
69 binary mode and leave *encoding* unspecified.) The available modes are:
Georg Brandl014197c2008-04-09 18:40:51 +000070
71 ========= ===============================================================
72 Character Meaning
73 --------- ---------------------------------------------------------------
74 ``'r'`` open for reading (default)
75 ``'w'`` open for writing, truncating the file first
76 ``'a'`` open for writing, appending to the end of the file if it exists
77 ``'b'`` binary mode
78 ``'t'`` text mode (default)
79 ``'+'`` open a disk file for updating (reading and writing)
Mark Summerfielde6d5f302008-04-21 10:29:45 +000080 ``'U'`` universal newline mode (for backwards compatibility; should
81 not be used in new code)
Georg Brandl014197c2008-04-09 18:40:51 +000082 ========= ===============================================================
83
84 The default mode is ``'rt'`` (open for reading text). For binary random
85 access, the mode ``'w+b'`` opens and truncates the file to 0 bytes, while
86 ``'r+b'`` opens the file without truncation.
87
Benjamin Peterson2c5f8282008-04-13 00:27:46 +000088 Python distinguishes between files opened in binary and text modes, even when
89 the underlying operating system doesn't. Files opened in binary mode
Mark Summerfielde6d5f302008-04-21 10:29:45 +000090 (including ``'b'`` in the *mode* argument) return contents as ``bytes``
Benjamin Peterson2c5f8282008-04-13 00:27:46 +000091 objects without any decoding. In text mode (the default, or when ``'t'`` is
Mark Summerfielde6d5f302008-04-21 10:29:45 +000092 included in the *mode* argument), the contents of the file are returned as
Benjamin Peterson2c5f8282008-04-13 00:27:46 +000093 strings, the bytes having been first decoded using a platform-dependent
94 encoding or using the specified *encoding* if given.
Benjamin Petersondd219122008-04-11 21:17:32 +000095
96 *buffering* is an optional integer used to set the buffering policy. By
Benjamin Peterson2c5f8282008-04-13 00:27:46 +000097 default full buffering is on. Pass 0 to switch buffering off (only allowed
98 in binary mode), 1 to set line buffering, and an integer > 1 for full
99 buffering.
Georg Brandl014197c2008-04-09 18:40:51 +0000100
101 *encoding* is the name of the encoding used to decode or encode the file.
Benjamin Petersondd219122008-04-11 21:17:32 +0000102 This should only be used in text mode. The default encoding is platform
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000103 dependent, but any encoding supported by Python can be used. See the
Benjamin Petersondd219122008-04-11 21:17:32 +0000104 :mod:`codecs` module for the list of supported encodings.
Georg Brandl014197c2008-04-09 18:40:51 +0000105
Benjamin Petersonb85a5842008-04-13 21:39:58 +0000106 *errors* is an optional string that specifies how encoding and decoding
Christian Heimesa342c012008-04-20 21:01:16 +0000107 errors are to be handled. Pass ``'strict'`` to raise a :exc:`ValueError`
108 exception if there is an encoding error (the default of ``None`` has the same
109 effect), or pass ``'ignore'`` to ignore errors. (Note that ignoring encoding
110 errors can lead to data loss.) ``'replace'`` causes a replacement marker
111 (such as ``'?'``) to be inserted where there is malformed data. When
112 writing, ``'xmlcharrefreplace'`` (replace with the appropriate XML character
113 reference) or ``'backslashreplace'`` (replace with backslashed escape
114 sequences) can be used. Any other error handling name that has been
115 registered with :func:`codecs.register_error` is also valid.
Georg Brandl014197c2008-04-09 18:40:51 +0000116
117 *newline* controls how universal newlines works (it only applies to text
118 mode). It can be ``None``, ``''``, ``'\n'``, ``'\r'``, and ``'\r\n'``. It
119 works as follows:
120
121 * On input, if *newline* is ``None``, universal newlines mode is enabled.
122 Lines in the input can end in ``'\n'``, ``'\r'``, or ``'\r\n'``, and these
123 are translated into ``'\n'`` before being returned to the caller. If it is
124 ``''``, universal newline mode is enabled, but line endings are returned to
125 the caller untranslated. If it has any of the other legal values, input
126 lines are only terminated by the given string, and the line ending is
127 returned to the caller untranslated.
128
129 * On output, if *newline* is ``None``, any ``'\n'`` characters written are
130 translated to the system default line separator, :data:`os.linesep`. If
131 *newline* is ``''``, no translation takes place. If *newline* is any of
132 the other legal values, any ``'\n'`` characters written are translated to
133 the given string.
134
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000135 If *closefd* is ``False`` and a file descriptor rather than a
136 filename was given, the underlying file descriptor will be kept open
137 when the file is closed. If a filename is given *closefd* has no
138 effect but must be ``True`` (the default).
Georg Brandl014197c2008-04-09 18:40:51 +0000139
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000140 The type of file object returned by the :func:`open` function depends
141 on the mode. When :func:`open` is used to open a file in a text mode
142 (``'w'``, ``'r'``, ``'wt'``, ``'rt'``, etc.), it returns a
143 :class:`TextIOWrapper`. When used to open a file in a binary mode,
144 the returned class varies: in read binary mode, it returns a
145 :class:`BufferedReader`; in write binary and append binary modes, it
146 returns a :class:`BufferedWriter`, and in read/write mode, it returns
147 a :class:`BufferedRandom`.
Georg Brandl014197c2008-04-09 18:40:51 +0000148
149 It is also possible to use a string or bytearray as a file for both reading
Benjamin Petersondd219122008-04-11 21:17:32 +0000150 and writing. For strings :class:`StringIO` can be used like a file opened in
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000151 a text mode, and for bytearrays a :class:`BytesIO` can be used like a
152 file opened in a binary mode.
Georg Brandl014197c2008-04-09 18:40:51 +0000153
154
155.. exception:: BlockingIOError
156
157 Error raised when blocking would occur on a non-blocking stream. It inherits
158 :exc:`IOError`.
159
160 In addition to those of :exc:`IOError`, :exc:`BlockingIOError` has one
161 attribute:
162
163 .. attribute:: characters_written
164
165 An integer containing the number of characters written to the stream
166 before it blocked.
167
168
169.. exception:: UnsupportedOperation
170
171 An exception inheriting :exc:`IOError` and :exc:`ValueError` that is raised
172 when an unsupported operation is called on a stream.
173
174
175I/O Base Classes
176----------------
177
178.. class:: IOBase
179
180 The abstract base class for all I/O classes, acting on streams of bytes.
181 There is no public constructor.
182
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000183 This class provides empty abstract implementations for many methods
184 that derived classes can override selectively; the default
185 implementations represent a file that cannot be read, written or
186 seeked.
Georg Brandl014197c2008-04-09 18:40:51 +0000187
188 Even though :class:`IOBase` does not declare :meth:`read`, :meth:`readinto`,
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000189 or :meth:`write` because their signatures will vary, implementations and
190 clients should consider those methods part of the interface. Also,
191 implementations may raise a :exc:`IOError` when operations they do not
192 support are called.
Georg Brandl014197c2008-04-09 18:40:51 +0000193
194 The basic type used for binary data read from or written to a file is
195 :class:`bytes`. :class:`bytearray`\s are accepted too, and in some cases
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000196 (such as :class:`readinto`) required. Text I/O classes work with
197 :class:`str` data.
Georg Brandl014197c2008-04-09 18:40:51 +0000198
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000199 Note that calling any method (even inquiries) on a closed stream is
200 undefined. Implementations may raise :exc:`IOError` in this case.
Georg Brandl014197c2008-04-09 18:40:51 +0000201
202 IOBase (and its subclasses) support the iterator protocol, meaning that an
203 :class:`IOBase` object can be iterated over yielding the lines in a stream.
204
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000205 IOBase is also a context manager and therefore supports the
206 :keyword:`with` statement. In this example, *file* is closed after the
207 :keyword:`with` statement's suite is finished---even if an exception occurs::
Georg Brandl014197c2008-04-09 18:40:51 +0000208
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000209 with open('spam.txt', 'w') as file:
210 file.write('Spam and eggs!')
Georg Brandl014197c2008-04-09 18:40:51 +0000211
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000212 :class:`IOBase` provides these data attributes and methods:
Georg Brandl014197c2008-04-09 18:40:51 +0000213
214 .. method:: close()
215
Christian Heimesecc42a22008-11-05 19:30:32 +0000216 Flush and close this stream. This method has no effect if the file is
Georg Brandl48310cd2009-01-03 21:18:54 +0000217 already closed. Once the file is closed, any operation on the file
Christian Heimesecc42a22008-11-05 19:30:32 +0000218 (e.g. reading or writing) will raise an :exc:`IOError`. The internal
219 file descriptor isn't closed if *closefd* was False.
Georg Brandl014197c2008-04-09 18:40:51 +0000220
221 .. attribute:: closed
222
223 True if the stream is closed.
224
225 .. method:: fileno()
226
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000227 Return the underlying file descriptor (an integer) of the stream if it
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000228 exists. An :exc:`IOError` is raised if the IO object does not use a file
Georg Brandl014197c2008-04-09 18:40:51 +0000229 descriptor.
230
231 .. method:: flush()
232
Benjamin Petersonb85a5842008-04-13 21:39:58 +0000233 Flush the write buffers of the stream if applicable. This does nothing
234 for read-only and non-blocking streams.
Georg Brandl014197c2008-04-09 18:40:51 +0000235
236 .. method:: isatty()
237
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000238 Return ``True`` if the stream is interactive (i.e., connected to
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000239 a terminal/tty device).
Georg Brandl014197c2008-04-09 18:40:51 +0000240
241 .. method:: readable()
242
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000243 Return ``True`` if the stream can be read from. If False, :meth:`read`
244 will raise :exc:`IOError`.
Georg Brandl014197c2008-04-09 18:40:51 +0000245
246 .. method:: readline([limit])
247
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000248 Read and return one line from the stream. If *limit* is specified, at
249 most *limit* bytes will be read.
Georg Brandl014197c2008-04-09 18:40:51 +0000250
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000251 The line terminator is always ``b'\n'`` for binary files; for text files,
Benjamin Petersonb85a5842008-04-13 21:39:58 +0000252 the *newlines* argument to :func:`open` can be used to select the line
Georg Brandl014197c2008-04-09 18:40:51 +0000253 terminator(s) recognized.
254
255 .. method:: readlines([hint])
256
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000257 Read and return a list of lines from the stream. *hint* can be specified
258 to control the number of lines read: no more lines will be read if the
259 total size (in bytes/characters) of all lines so far exceeds *hint*.
Georg Brandl014197c2008-04-09 18:40:51 +0000260
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000261 .. method:: seek(offset[, whence])
262
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000263 Change the stream position to the given byte *offset*. *offset* is
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000264 interpreted relative to the position indicated by *whence*. Values for
265 *whence* are:
266
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000267 * ``0`` -- start of the stream (the default); *offset* should be zero or positive
268 * ``1`` -- current stream position; *offset* may be negative
269 * ``2`` -- end of the stream; *offset* is usually negative
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000270
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000271 Return the new absolute position.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000272
Georg Brandl014197c2008-04-09 18:40:51 +0000273 .. method:: seekable()
274
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000275 Return ``True`` if the stream supports random access. If ``False``,
276 :meth:`seek`, :meth:`tell` and :meth:`truncate` will raise :exc:`IOError`.
Georg Brandl014197c2008-04-09 18:40:51 +0000277
278 .. method:: tell()
279
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000280 Return the current stream position.
Georg Brandl014197c2008-04-09 18:40:51 +0000281
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000282 .. method:: truncate([size])
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000283
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000284 Truncate the file to at most *size* bytes. *size* defaults to the current
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000285 file position, as returned by :meth:`tell`.
286
Georg Brandl014197c2008-04-09 18:40:51 +0000287 .. method:: writable()
288
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000289 Return ``True`` if the stream supports writing. If ``False``,
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000290 :meth:`write` and :meth:`truncate` will raise :exc:`IOError`.
Georg Brandl014197c2008-04-09 18:40:51 +0000291
292 .. method:: writelines(lines)
293
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000294 Write a list of lines to the stream. Line separators are not added, so it
295 is usual for each of the lines provided to have a line separator at the
296 end.
Georg Brandl014197c2008-04-09 18:40:51 +0000297
298
299.. class:: RawIOBase
300
301 Base class for raw binary I/O. It inherits :class:`IOBase`. There is no
302 public constructor.
303
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000304 In addition to the attributes and methods from :class:`IOBase`,
305 RawIOBase provides the following methods:
Georg Brandl014197c2008-04-09 18:40:51 +0000306
Benjamin Petersonb47aace2008-04-09 21:38:38 +0000307 .. method:: read([n])
Georg Brandl014197c2008-04-09 18:40:51 +0000308
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000309 Read and return all the bytes from the stream until EOF, or if *n* is
310 specified, up to *n* bytes. Only one system call is ever made. An empty
311 bytes object is returned on EOF; ``None`` is returned if the object is set
312 not to block and has no data to read.
Georg Brandl014197c2008-04-09 18:40:51 +0000313
Benjamin Petersonb47aace2008-04-09 21:38:38 +0000314 .. method:: readall()
Georg Brandl014197c2008-04-09 18:40:51 +0000315
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000316 Read and return all the bytes from the stream until EOF, using multiple
317 calls to the stream if necessary.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000318
319 .. method:: readinto(b)
320
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000321 Read up to len(b) bytes into bytearray *b* and return the number of bytes
322 read.
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000323
324 .. method:: write(b)
325
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000326 Write the given bytes or bytearray object, *b*, to the underlying raw
327 stream and return the number of bytes written (This is never less than
328 ``len(b)``, since if the write fails, an :exc:`IOError` will be raised).
Georg Brandl014197c2008-04-09 18:40:51 +0000329
330
Georg Brandl014197c2008-04-09 18:40:51 +0000331.. class:: BufferedIOBase
332
333 Base class for streams that support buffering. It inherits :class:`IOBase`.
334 There is no public constructor.
335
336 The main difference with :class:`RawIOBase` is that the :meth:`read` method
337 supports omitting the *size* argument, and does not have a default
338 implementation that defers to :meth:`readinto`.
339
340 In addition, :meth:`read`, :meth:`readinto`, and :meth:`write` may raise
341 :exc:`BlockingIOError` if the underlying raw stream is in non-blocking mode
342 and not ready; unlike their raw counterparts, they will never return
343 ``None``.
344
345 A typical implementation should not inherit from a :class:`RawIOBase`
346 implementation, but wrap one like :class:`BufferedWriter` and
347 :class:`BufferedReader`.
348
349 :class:`BufferedIOBase` provides or overrides these methods in addition to
350 those from :class:`IOBase`:
351
352 .. method:: read([n])
353
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000354 Read and return up to *n* bytes. If the argument is omitted, ``None``, or
Georg Brandl014197c2008-04-09 18:40:51 +0000355 negative, data is read and returned until EOF is reached. An empty bytes
356 object is returned if the stream is already at EOF.
357
358 If the argument is positive, and the underlying raw stream is not
359 interactive, multiple raw reads may be issued to satisfy the byte count
360 (unless EOF is reached first). But for interactive raw streams, at most
361 one raw read will be issued, and a short result does not imply that EOF is
362 imminent.
363
364 A :exc:`BlockingIOError` is raised if the underlying raw stream has no
365 data at the moment.
366
367 .. method:: readinto(b)
368
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000369 Read up to len(b) bytes into bytearray *b* and return the number of bytes
Georg Brandl014197c2008-04-09 18:40:51 +0000370 read.
371
372 Like :meth:`read`, multiple reads may be issued to the underlying raw
373 stream, unless the latter is 'interactive.'
374
375 A :exc:`BlockingIOError` is raised if the underlying raw stream has no
376 data at the moment.
377
Georg Brandl014197c2008-04-09 18:40:51 +0000378 .. method:: write(b)
379
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000380 Write the given bytes or bytearray object, *b*, to the underlying raw
381 stream and return the number of bytes written (never less than ``len(b)``,
382 since if the write fails an :exc:`IOError` will be raised).
Georg Brandl014197c2008-04-09 18:40:51 +0000383
384 A :exc:`BlockingIOError` is raised if the buffer is full, and the
385 underlying raw stream cannot accept more data at the moment.
386
387
Benjamin Petersonaa069002009-01-23 03:26:36 +0000388Raw File I/O
389------------
390
391.. class:: FileIO(name[, mode])
392
393 :class:`FileIO` represents a file containing bytes data. It implements
394 the :class:`RawIOBase` interface (and therefore the :class:`IOBase`
395 interface, too).
396
397 The *mode* can be ``'r'``, ``'w'`` or ``'a'`` for reading (default), writing,
398 or appending. The file will be created if it doesn't exist when opened for
399 writing or appending; it will be truncated when opened for writing. Add a
400 ``'+'`` to the mode to allow simultaneous reading and writing.
401
402 In addition to the attributes and methods from :class:`IOBase` and
403 :class:`RawIOBase`, :class:`FileIO` provides the following data
404 attributes and methods:
405
406 .. attribute:: mode
407
408 The mode as given in the constructor.
409
410 .. attribute:: name
411
412 The file name. This is the file descriptor of the file when no name is
413 given in the constructor.
414
415 .. method:: read([n])
416
417 Read and return at most *n* bytes. Only one system call is made, so it is
418 possible that less data than was requested is returned. Use :func:`len`
419 on the returned bytes object to see how many bytes were actually returned.
420 (In non-blocking mode, ``None`` is returned when no data is available.)
421
422 .. method:: readall()
423
424 Read and return the entire file's contents in a single bytes object. As
425 much as immediately available is returned in non-blocking mode. If the
426 EOF has been reached, ``b''`` is returned.
427
428 .. method:: write(b)
429
430 Write the bytes or bytearray object, *b*, to the file, and return
431 the number actually written. Only one system call is made, so it
432 is possible that only some of the data is written.
433
434 Note that the inherited ``readinto()`` method should not be used on
435 :class:`FileIO` objects.
436
437
438Buffered Streams
439----------------
440
Georg Brandl014197c2008-04-09 18:40:51 +0000441.. class:: BytesIO([initial_bytes])
442
443 A stream implementation using an in-memory bytes buffer. It inherits
444 :class:`BufferedIOBase`.
445
446 The argument *initial_bytes* is an optional initial bytearray.
447
448 :class:`BytesIO` provides or overrides these methods in addition to those
449 from :class:`BufferedIOBase` and :class:`IOBase`:
450
451 .. method:: getvalue()
452
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000453 Return ``bytes`` containing the entire contents of the buffer.
Georg Brandl014197c2008-04-09 18:40:51 +0000454
455 .. method:: read1()
456
Benjamin Peterson9efcc4b2008-04-14 21:30:21 +0000457 In :class:`BytesIO`, this is the same as :meth:`read`.
Georg Brandl014197c2008-04-09 18:40:51 +0000458
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000459 .. method:: truncate([size])
Georg Brandl014197c2008-04-09 18:40:51 +0000460
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000461 Truncate the buffer to at most *size* bytes. *size* defaults to the
462 current stream position, as returned by :meth:`tell`.
Georg Brandl014197c2008-04-09 18:40:51 +0000463
464
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000465.. class:: BufferedReader(raw[, buffer_size])
Georg Brandl014197c2008-04-09 18:40:51 +0000466
Benjamin Peterson13d4a612008-04-13 23:46:27 +0000467 A buffer for a readable, sequential :class:`RawIOBase` object. It inherits
Georg Brandl014197c2008-04-09 18:40:51 +0000468 :class:`BufferedIOBase`.
469
470 The constructor creates a :class:`BufferedReader` for the given readable
471 *raw* stream and *buffer_size*. If *buffer_size* is omitted,
472 :data:`DEFAULT_BUFFER_SIZE` is used.
473
474 :class:`BufferedReader` provides or overrides these methods in addition to
475 those from :class:`BufferedIOBase` and :class:`IOBase`:
476
477 .. method:: peek([n])
478
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000479 Return 1 (or *n* if specified) bytes from a buffer without advancing the
480 position. Only a single read on the raw stream is done to satisfy the
481 call. The number of bytes returned may be less than requested since at
482 most all the buffer's bytes from the current position to the end are
483 returned.
Georg Brandl014197c2008-04-09 18:40:51 +0000484
485 .. method:: read([n])
486
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000487 Read and return *n* bytes, or if *n* is not given or negative, until EOF
Georg Brandl014197c2008-04-09 18:40:51 +0000488 or if the read call would block in non-blocking mode.
489
490 .. method:: read1(n)
491
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000492 Read and return up to *n* bytes with only one call on the raw stream. If
Georg Brandl014197c2008-04-09 18:40:51 +0000493 at least one byte is buffered, only buffered bytes are returned.
494 Otherwise, one raw stream read call is made.
495
496
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000497.. class:: BufferedWriter(raw[, buffer_size[, max_buffer_size]])
Georg Brandl014197c2008-04-09 18:40:51 +0000498
499 A buffer for a writeable sequential RawIO object. It inherits
500 :class:`BufferedIOBase`.
501
502 The constructor creates a :class:`BufferedWriter` for the given writeable
503 *raw* stream. If the *buffer_size* is not given, it defaults to
504 :data:`DEAFULT_BUFFER_SIZE`. If *max_buffer_size* is omitted, it defaults to
505 twice the buffer size.
506
507 :class:`BufferedWriter` provides or overrides these methods in addition to
508 those from :class:`BufferedIOBase` and :class:`IOBase`:
509
510 .. method:: flush()
511
512 Force bytes held in the buffer into the raw stream. A
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000513 :exc:`BlockingIOError` should be raised if the raw stream blocks.
Georg Brandl014197c2008-04-09 18:40:51 +0000514
515 .. method:: write(b)
516
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000517 Write the bytes or bytearray object, *b*, onto the raw stream and return
518 the number of bytes written. A :exc:`BlockingIOError` is raised when the
519 raw stream blocks.
Georg Brandl014197c2008-04-09 18:40:51 +0000520
521
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000522.. class:: BufferedRWPair(reader, writer[, buffer_size[, max_buffer_size]])
Georg Brandl014197c2008-04-09 18:40:51 +0000523
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000524 A combined buffered writer and reader object for a raw stream that can be
525 written to and read from. It has and supports both :meth:`read`, :meth:`write`,
526 and their variants. This is useful for sockets and two-way pipes.
527 It inherits :class:`BufferedIOBase`.
Georg Brandl014197c2008-04-09 18:40:51 +0000528
529 *reader* and *writer* are :class:`RawIOBase` objects that are readable and
530 writeable respectively. If the *buffer_size* is omitted it defaults to
531 :data:`DEFAULT_BUFFER_SIZE`. The *max_buffer_size* (for the buffered writer)
532 defaults to twice the buffer size.
533
534 :class:`BufferedRWPair` implements all of :class:`BufferedIOBase`\'s methods.
535
536
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000537.. class:: BufferedRandom(raw[, buffer_size[, max_buffer_size]])
Georg Brandl014197c2008-04-09 18:40:51 +0000538
539 A buffered interface to random access streams. It inherits
540 :class:`BufferedReader` and :class:`BufferedWriter`.
541
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000542 The constructor creates a reader and writer for a seekable raw stream, given
Georg Brandl014197c2008-04-09 18:40:51 +0000543 in the first argument. If the *buffer_size* is omitted it defaults to
544 :data:`DEFAULT_BUFFER_SIZE`. The *max_buffer_size* (for the buffered writer)
545 defaults to twice the buffer size.
546
547 :class:`BufferedRandom` is capable of anything :class:`BufferedReader` or
548 :class:`BufferedWriter` can do.
549
550
551Text I/O
552--------
553
554.. class:: TextIOBase
555
556 Base class for text streams. This class provides a character and line based
557 interface to stream I/O. There is no :meth:`readinto` method because
558 Python's character strings are immutable. It inherits :class:`IOBase`.
559 There is no public constructor.
560
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000561 :class:`TextIOBase` provides or overrides these data attributes and
562 methods in addition to those from :class:`IOBase`:
Georg Brandl014197c2008-04-09 18:40:51 +0000563
564 .. attribute:: encoding
565
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000566 The name of the encoding used to decode the stream's bytes into
Georg Brandl014197c2008-04-09 18:40:51 +0000567 strings, and to encode strings into bytes.
568
569 .. attribute:: newlines
570
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000571 A string, a tuple of strings, or ``None``, indicating the newlines
Georg Brandl014197c2008-04-09 18:40:51 +0000572 translated so far.
573
574 .. method:: read(n)
575
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000576 Read and return at most *n* characters from the stream as a single
577 :class:`str`. If *n* is negative or ``None``, reads to EOF.
Georg Brandl014197c2008-04-09 18:40:51 +0000578
579 .. method:: readline()
580
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000581 Read until newline or EOF and return a single ``str``. If the stream is
582 already at EOF, an empty string is returned.
Georg Brandl014197c2008-04-09 18:40:51 +0000583
Georg Brandl014197c2008-04-09 18:40:51 +0000584 .. method:: write(s)
585
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000586 Write the string *s* to the stream and return the number of characters
587 written.
Georg Brandl014197c2008-04-09 18:40:51 +0000588
589
590.. class:: TextIOWrapper(buffer[, encoding[, errors[, newline[, line_buffering]]]])
591
592 A buffered text stream over a :class:`BufferedIOBase` raw stream, *buffer*.
593 It inherits :class:`TextIOBase`.
594
595 *encoding* gives the name of the encoding that the stream will be decoded or
596 encoded with. It defaults to :func:`locale.getpreferredencoding`.
597
Benjamin Petersonb85a5842008-04-13 21:39:58 +0000598 *errors* is an optional string that specifies how encoding and decoding
599 errors are to be handled. Pass ``'strict'`` to raise a :exc:`ValueError`
600 exception if there is an encoding error (the default of ``None`` has the same
601 effect), or pass ``'ignore'`` to ignore errors. (Note that ignoring encoding
602 errors can lead to data loss.) ``'replace'`` causes a replacement marker
Christian Heimesa342c012008-04-20 21:01:16 +0000603 (such as ``'?'``) to be inserted where there is malformed data. When
604 writing, ``'xmlcharrefreplace'`` (replace with the appropriate XML character
605 reference) or ``'backslashreplace'`` (replace with backslashed escape
606 sequences) can be used. Any other error handling name that has been
607 registered with :func:`codecs.register_error` is also valid.
Georg Brandl014197c2008-04-09 18:40:51 +0000608
609 *newline* can be ``None``, ``''``, ``'\n'``, ``'\r'``, or ``'\r\n'``. It
610 controls the handling of line endings. If it is ``None``, universal newlines
611 is enabled. With this enabled, on input, the lines endings ``'\n'``,
612 ``'\r'``, or ``'\r\n'`` are translated to ``'\n'`` before being returned to
613 the caller. Conversely, on output, ``'\n'`` is translated to the system
614 default line seperator, :data:`os.linesep`. If *newline* is any other of its
615 legal values, that newline becomes the newline when the file is read and it
616 is returned untranslated. On output, ``'\n'`` is converted to the *newline*.
617
618 If *line_buffering* is ``True``, :meth:`flush` is implied when a call to
619 write contains a newline character.
620
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000621 :class:`TextIOWrapper` provides these data attributes in addition to those of
Georg Brandl014197c2008-04-09 18:40:51 +0000622 :class:`TextIOBase` and its parents:
623
624 .. attribute:: errors
625
626 The encoding and decoding error setting.
627
628 .. attribute:: line_buffering
629
630 Whether line buffering is enabled.
Georg Brandl48310cd2009-01-03 21:18:54 +0000631
Georg Brandl014197c2008-04-09 18:40:51 +0000632
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000633.. class:: StringIO([initial_value[, encoding[, errors[, newline]]]])
Georg Brandl014197c2008-04-09 18:40:51 +0000634
Georg Brandl2932d932008-05-30 06:27:09 +0000635 An in-memory stream for text. It inherits :class:`TextIOWrapper`.
Georg Brandl014197c2008-04-09 18:40:51 +0000636
Georg Brandl2932d932008-05-30 06:27:09 +0000637 Create a new StringIO stream with an initial value, encoding, error handling,
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000638 and newline setting. See :class:`TextIOWrapper`\'s constructor for more
Georg Brandl014197c2008-04-09 18:40:51 +0000639 information.
640
Mark Summerfielde6d5f302008-04-21 10:29:45 +0000641 :class:`StringIO` provides this method in addition to those from
Georg Brandl014197c2008-04-09 18:40:51 +0000642 :class:`TextIOWrapper` and its parents:
643
644 .. method:: getvalue()
645
Georg Brandl2932d932008-05-30 06:27:09 +0000646 Return a ``str`` containing the entire contents of the buffer at any
647 time before the :class:`StringIO` object's :meth:`close` method is
648 called.
Georg Brandl014197c2008-04-09 18:40:51 +0000649
Georg Brandl2932d932008-05-30 06:27:09 +0000650 Example usage::
651
652 import io
653
654 output = io.StringIO()
655 output.write('First line.\n')
656 print('Second line.', file=output)
657
658 # Retrieve file contents -- this will be
659 # 'First line.\nSecond line.\n'
660 contents = output.getvalue()
661
Georg Brandl48310cd2009-01-03 21:18:54 +0000662 # Close object and discard memory buffer --
Georg Brandl2932d932008-05-30 06:27:09 +0000663 # .getvalue() will now raise an exception.
664 output.close()
Georg Brandl014197c2008-04-09 18:40:51 +0000665
666.. class:: IncrementalNewlineDecoder
667
Benjamin Peterson2c5f8282008-04-13 00:27:46 +0000668 A helper codec that decodes newlines for universal newlines mode. It
669 inherits :class:`codecs.IncrementalDecoder`.
Georg Brandl014197c2008-04-09 18:40:51 +0000670