blob: af86c353f61d7fa1f7fff39ba3889746f89d7eb7 [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>
9.. sectionauthor:: Benjamin Peterson
10.. versionadded:: 2.6
11
12The :mod:`io` module provides the Python interfaces to stream handling. The
13builtin :func:`open` function is defined in this module.
14
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
17seperation between reading and writing to streams; implementations are allowed
18to 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
Benjamin Peterson53be57e2008-04-19 19:34:05 +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
Benjamin Peterson53be57e2008-04-19 19:34:05 +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
97 *buffering* is an optional integer used to set the buffering policy. By
98 default full buffering is on. Pass 0 to switch buffering off (only allowed
99 in binary mode), 1 to set line buffering, and an integer > 1 for full
100 buffering.
101
102 *encoding* is the name of the encoding used to decode or encode the file.
103 This should only be used in text mode. The default encoding is platform
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000104 dependent, but any encoding supported by Python can be used. See the
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000105 :mod:`codecs` module for the list of supported encodings.
106
Benjamin Peterson53be57e2008-04-19 19:34:05 +0000107 *errors* is an optional string that specifies how encoding and decoding
Benjamin Petersona7d09032008-04-19 19:47:34 +0000108 errors are to be handled. Pass ``'strict'`` to raise a :exc:`ValueError`
109 exception if there is an encoding error (the default of ``None`` has the same
110 effect), or pass ``'ignore'`` to ignore errors. (Note that ignoring encoding
111 errors can lead to data loss.) ``'replace'`` causes a replacement marker
112 (such as ``'?'``) to be inserted where there is malformed data. When
113 writing, ``'xmlcharrefreplace'`` (replace with the appropriate XML character
114 reference) or ``'backslashreplace'`` (replace with backslashed escape
115 sequences) can be used. Any other error handling name that has been
116 registered with :func:`codecs.register_error` is also valid.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000117
118 *newline* controls how universal newlines works (it only applies to text
119 mode). It can be ``None``, ``''``, ``'\n'``, ``'\r'``, and ``'\r\n'``. It
120 works as follows:
121
122 * On input, if *newline* is ``None``, universal newlines mode is enabled.
123 Lines in the input can end in ``'\n'``, ``'\r'``, or ``'\r\n'``, and these
124 are translated into ``'\n'`` before being returned to the caller. If it is
125 ``''``, universal newline mode is enabled, but line endings are returned to
126 the caller untranslated. If it has any of the other legal values, input
127 lines are only terminated by the given string, and the line ending is
128 returned to the caller untranslated.
129
130 * On output, if *newline* is ``None``, any ``'\n'`` characters written are
131 translated to the system default line separator, :data:`os.linesep`. If
132 *newline* is ``''``, no translation takes place. If *newline* is any of
133 the other legal values, any ``'\n'`` characters written are translated to
134 the given string.
135
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000136 If *closefd* is ``False`` and a file descriptor rather than a
137 filename was given, the underlying file descriptor will be kept open
138 when the file is closed. If a filename is given *closefd* has no
139 effect but must be ``True`` (the default).
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000140
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000141 The type of file object returned by the :func:`open` function depends
142 on the mode. When :func:`open` is used to open a file in a text mode
143 (``'w'``, ``'r'``, ``'wt'``, ``'rt'``, etc.), it returns a
144 :class:`TextIOWrapper`. When used to open a file in a binary mode,
145 the returned class varies: in read binary mode, it returns a
146 :class:`BufferedReader`; in write binary and append binary modes, it
147 returns a :class:`BufferedWriter`, and in read/write mode, it returns
148 a :class:`BufferedRandom`.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000149
150 It is also possible to use a string or bytearray as a file for both reading
151 and writing. For strings :class:`StringIO` can be used like a file opened in
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000152 a text mode, and for bytearrays a :class:`BytesIO` can be used like a
153 file opened in a binary mode.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000154
155
156.. exception:: BlockingIOError
157
158 Error raised when blocking would occur on a non-blocking stream. It inherits
159 :exc:`IOError`.
160
161 In addition to those of :exc:`IOError`, :exc:`BlockingIOError` has one
162 attribute:
163
164 .. attribute:: characters_written
165
166 An integer containing the number of characters written to the stream
167 before it blocked.
168
169
170.. exception:: UnsupportedOperation
171
172 An exception inheriting :exc:`IOError` and :exc:`ValueError` that is raised
173 when an unsupported operation is called on a stream.
174
175
176I/O Base Classes
177----------------
178
179.. class:: IOBase
180
181 The abstract base class for all I/O classes, acting on streams of bytes.
182 There is no public constructor.
183
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000184 This class provides empty abstract implementations for many methods
185 that derived classes can override selectively; the default
186 implementations represent a file that cannot be read, written or
187 seeked.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000188
189 Even though :class:`IOBase` does not declare :meth:`read`, :meth:`readinto`,
190 or :meth:`write` because their signatures will vary, implementations and
191 clients should consider those methods part of the interface. Also,
192 implementations may raise a :exc:`IOError` when operations they do not
193 support are called.
194
195 The basic type used for binary data read from or written to a file is
196 :class:`bytes`. :class:`bytearray`\s are accepted too, and in some cases
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000197 (such as :class:`readinto`) required. Text I/O classes work with
198 :class:`str` data.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000199
200 Note that calling any method (even inquiries) on a closed stream is
201 undefined. Implementations may raise :exc:`IOError` in this case.
202
203 IOBase (and its subclasses) support the iterator protocol, meaning that an
204 :class:`IOBase` object can be iterated over yielding the lines in a stream.
205
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000206 IOBase is also a context manager and therefore supports the
207 :keyword:`with` statement. In this example, *file* is closed after the
208 :keyword:`with` statement's suite is finished---even if an exception occurs::
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000209
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000210 with open('spam.txt', 'w') as file:
211 file.write('Spam and eggs!')
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000212
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000213 :class:`IOBase` provides these data attributes and methods:
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000214
215 .. method:: close()
216
217 Flush and close this stream. This method has no effect if the file is
218 already closed.
219
220 .. attribute:: closed
221
222 True if the stream is closed.
223
224 .. method:: fileno()
225
226 Return the underlying file descriptor (an integer) of the stream, if it
227 exists. An :exc:`IOError` is raised if the IO object does not use a file
228 descriptor.
229
230 .. method:: flush()
231
Benjamin Peterson53be57e2008-04-19 19:34:05 +0000232 Flush the write buffers of the stream if applicable. This does nothing
233 for read-only and non-blocking streams.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000234
235 .. method:: isatty()
236
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000237 Returns ``True`` if the stream is interactive (i.e., connected to
238 a terminal/tty device).
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000239
240 .. method:: readable()
241
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000242 Returns ``True`` if the stream can be read from. If False,
243 :meth:`read` will raise :exc:`IOError`.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000244
245 .. method:: readline([limit])
246
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000247 Reads and returns one line from the stream. If *limit* is
248 specified, at most *limit* bytes will be read.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000249
250 The line terminator is always ``b'\n'`` for binary files; for text files,
Benjamin Peterson53be57e2008-04-19 19:34:05 +0000251 the *newlines* argument to :func:`open` can be used to select the line
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000252 terminator(s) recognized.
253
254 .. method:: readlines([hint])
255
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000256 Returns a list of lines from the stream. *hint* can be specified to
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000257 control the number of lines read: no more lines will be read if the total
258 size (in bytes/characters) of all lines so far exceeds *hint*.
259
260 .. method:: seek(offset[, whence])
261
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000262 Change the stream position to the given byte *offset*. *offset* is
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000263 interpreted relative to the position indicated by *whence*. Values for
264 *whence* are:
265
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000266 * ``0`` -- start of the stream (the default); *offset* should be zero or positive
267 * ``1`` -- current stream position; *offset* may be negative
268 * ``2`` -- end of the stream; *offset* is usually negative
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000269
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000270 Returns the new absolute position.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000271
272 .. method:: seekable()
273
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000274 Returns ``True`` if the stream supports random access. If
275 ``False``, :meth:`seek`, :meth:`tell` and :meth:`truncate` will
276 raise :exc:`IOError`.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000277
278 .. method:: tell()
279
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000280 Returns the current stream position.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000281
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000282 .. method:: truncate([size])
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000283
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000284 Truncates the file to at most *size* bytes. *size* defaults to the current
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000285 file position, as returned by :meth:`tell`.
286
287 .. method:: writable()
288
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000289 Returns ``True`` if the stream supports writing. If ``False``,
290 :meth:`write` and :meth:`truncate` will raise :exc:`IOError`.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000291
292 .. method:: writelines(lines)
293
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000294 Writes a list of lines to the stream. Line separators are not
295 added, so it is usual for each of the lines provided to have a
296 line separator at the end.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +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
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000304 In addition to the attributes and methods from :class:`IOBase`,
305 RawIOBase provides the following methods:
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000306
307 .. method:: read([n])
308
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000309 Reads and returns all the bytes from the stream until EOF, or if *n* is
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000310 specified, up to *n* bytes. An empty bytes object is returned on EOF;
311 ``None`` is returned if the object is set not to block and has no data to
312 read.
313
314 .. method:: readall()
315
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000316 Reads and returns all the bytes from the stream until EOF, using
317 multiple calls to the stream if necessary.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000318
319 .. method:: readinto(b)
320
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000321 Reads up to len(b) bytes into bytearray *b* and returns the number
322 of bytes read.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000323
324 .. method:: write(b)
325
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000326 Writes the given bytes or bytearray object, *b*, to the underlying
327 raw stream and returns the number of bytes written (never less
328 than ``len(b)``, since if the write fails an :exc:`IOError` will
329 be raised).
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000330
331
332Raw File I/O
333------------
334
335.. class:: FileIO(name[, mode])
336
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000337 :class:`FileIO` represents a file containing bytes data. It implements
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000338 the :class:`RawIOBase` interface (and therefore the :class:`IOBase`
339 interface, too).
340
341 The *mode* can be ``'r'``, ``'w'`` or ``'a'`` for reading (default), writing,
342 or appending. The file will be created if it doesn't exist when opened for
343 writing or appending; it will be truncated when opened for writing. Add a
344 ``'+'`` to the mode to allow simultaneous reading and writing.
345
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000346 In addition to the attributes and methods from :class:`IOBase` and
347 :class:`RawIOBase`, :class:`FileIO` provides the following data
348 attributes and methods:
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000349
350 .. attribute:: mode
351
352 The mode as given in the constructor.
353
354 .. attribute:: name
355
356 The file name.
357
358 .. method:: read([n])
359
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000360 Reads and returns at most *n* bytes. Only one system call is made, so
361 it is possible that less data than was requested is returned. Call
362 :func:`len` on the returned bytes object to see how many bytes
363 were actually returned (In non-blocking mode, ``None`` is returned
364 when no data is available.)
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000365
366 .. method:: readall()
367
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000368 Reads and returns the entire file's contents in a single bytes
369 object. As much as immediately available is returned in
370 non-blocking mode. If the EOF has been reached, ``b''`` is
371 returned.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000372
373 .. method:: write(b)
374
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000375 Write the bytes or bytearray object, *b*, to the file, and return
376 the number actually written. Only one system call is made, so it
377 is possible that only some of the data is written.
378
379 Note that the inherited ``readinto()`` method should not be used on
380 :class:`FileIO` objects.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000381
382
383Buffered Streams
384----------------
385
386.. class:: BufferedIOBase
387
388 Base class for streams that support buffering. It inherits :class:`IOBase`.
389 There is no public constructor.
390
391 The main difference with :class:`RawIOBase` is that the :meth:`read` method
392 supports omitting the *size* argument, and does not have a default
393 implementation that defers to :meth:`readinto`.
394
395 In addition, :meth:`read`, :meth:`readinto`, and :meth:`write` may raise
396 :exc:`BlockingIOError` if the underlying raw stream is in non-blocking mode
397 and not ready; unlike their raw counterparts, they will never return
398 ``None``.
399
400 A typical implementation should not inherit from a :class:`RawIOBase`
401 implementation, but wrap one like :class:`BufferedWriter` and
402 :class:`BufferedReader`.
403
404 :class:`BufferedIOBase` provides or overrides these methods in addition to
405 those from :class:`IOBase`:
406
407 .. method:: read([n])
408
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000409 Reads and returns up to *n* bytes. If the argument is omitted, ``None``, or
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000410 negative, data is read and returned until EOF is reached. An empty bytes
411 object is returned if the stream is already at EOF.
412
413 If the argument is positive, and the underlying raw stream is not
414 interactive, multiple raw reads may be issued to satisfy the byte count
415 (unless EOF is reached first). But for interactive raw streams, at most
416 one raw read will be issued, and a short result does not imply that EOF is
417 imminent.
418
419 A :exc:`BlockingIOError` is raised if the underlying raw stream has no
420 data at the moment.
421
422 .. method:: readinto(b)
423
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000424 Reads up to len(b) bytes into bytearray *b* and returns the number of bytes
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000425 read.
426
427 Like :meth:`read`, multiple reads may be issued to the underlying raw
428 stream, unless the latter is 'interactive.'
429
430 A :exc:`BlockingIOError` is raised if the underlying raw stream has no
431 data at the moment.
432
433 .. method:: write(b)
434
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000435 Writes the given bytes or bytearray object, *b*, to the underlying
436 raw stream and returns the number of bytes written (never less than
437 ``len(b)``, since if the write fails an :exc:`IOError` will
438 be raised).
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000439
440 A :exc:`BlockingIOError` is raised if the buffer is full, and the
441 underlying raw stream cannot accept more data at the moment.
442
443
444.. class:: BytesIO([initial_bytes])
445
446 A stream implementation using an in-memory bytes buffer. It inherits
447 :class:`BufferedIOBase`.
448
449 The argument *initial_bytes* is an optional initial bytearray.
450
451 :class:`BytesIO` provides or overrides these methods in addition to those
452 from :class:`BufferedIOBase` and :class:`IOBase`:
453
454 .. method:: getvalue()
455
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000456 Returns a bytes object containing the entire contents of the
457 buffer.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000458
459 .. method:: read1()
460
Benjamin Peterson53be57e2008-04-19 19:34:05 +0000461 In :class:`BytesIO`, this is the same as :meth:`read`.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000462
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000463 .. method:: truncate([size])
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000464
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000465 Truncates the buffer to at most *size* bytes. *size* defaults to the current
Benjamin Peterson53be57e2008-04-19 19:34:05 +0000466 stream position, as returned by :meth:`tell`.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000467
468
469.. class:: BufferedReader(raw[, buffer_size])
470
Benjamin Peterson53be57e2008-04-19 19:34:05 +0000471 A buffer for a readable, sequential :class:`RawIOBase` object. It inherits
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000472 :class:`BufferedIOBase`.
473
474 The constructor creates a :class:`BufferedReader` for the given readable
475 *raw* stream and *buffer_size*. If *buffer_size* is omitted,
476 :data:`DEFAULT_BUFFER_SIZE` is used.
477
478 :class:`BufferedReader` provides or overrides these methods in addition to
479 those from :class:`BufferedIOBase` and :class:`IOBase`:
480
481 .. method:: peek([n])
482
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000483 Returns 1 (or *n* if specified) bytes from a buffer without
484 advancing the position. Only a single read on the raw stream is done to
485 satisfy the call. The number of bytes returned may be less than
486 requested since at most all the buffer's bytes from the current
487 position to the end are returned.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000488
489 .. method:: read([n])
490
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000491 Reads and returns *n* bytes, or if *n* is not given or negative, until EOF
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000492 or if the read call would block in non-blocking mode.
493
494 .. method:: read1(n)
495
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000496 Reads and returns up to *n* bytes with only one call on the raw stream. If
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000497 at least one byte is buffered, only buffered bytes are returned.
498 Otherwise, one raw stream read call is made.
499
500
501.. class:: BufferedWriter(raw[, buffer_size[, max_buffer_size]])
502
503 A buffer for a writeable sequential RawIO object. It inherits
504 :class:`BufferedIOBase`.
505
506 The constructor creates a :class:`BufferedWriter` for the given writeable
507 *raw* stream. If the *buffer_size* is not given, it defaults to
508 :data:`DEAFULT_BUFFER_SIZE`. If *max_buffer_size* is omitted, it defaults to
509 twice the buffer size.
510
511 :class:`BufferedWriter` provides or overrides these methods in addition to
512 those from :class:`BufferedIOBase` and :class:`IOBase`:
513
514 .. method:: flush()
515
516 Force bytes held in the buffer into the raw stream. A
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000517 :exc:`BlockingIOError` should be raised if the raw stream blocks.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000518
519 .. method:: write(b)
520
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000521 Writes the bytes or bytearray object, *b*, onto the raw stream and
522 returns the number of bytes written. A :exc:`BlockingIOError` is
523 raised when the raw stream blocks.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000524
525
526.. class:: BufferedRWPair(reader, writer[, buffer_size[, max_buffer_size]])
527
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000528 A combined buffered writer and reader object for a raw stream that can be
529 written to and read from. It has and supports both :meth:`read`, :meth:`write`,
530 and their variants. This is useful for sockets and two-way pipes.
531 It inherits :class:`BufferedIOBase`.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000532
533 *reader* and *writer* are :class:`RawIOBase` objects that are readable and
534 writeable respectively. If the *buffer_size* is omitted it defaults to
535 :data:`DEFAULT_BUFFER_SIZE`. The *max_buffer_size* (for the buffered writer)
536 defaults to twice the buffer size.
537
538 :class:`BufferedRWPair` implements all of :class:`BufferedIOBase`\'s methods.
539
540
541.. class:: BufferedRandom(raw[, buffer_size[, max_buffer_size]])
542
543 A buffered interface to random access streams. It inherits
544 :class:`BufferedReader` and :class:`BufferedWriter`.
545
546 The constructor creates a reader and writer for a seekable raw stream, given
547 in the first argument. If the *buffer_size* is omitted it defaults to
548 :data:`DEFAULT_BUFFER_SIZE`. The *max_buffer_size* (for the buffered writer)
549 defaults to twice the buffer size.
550
551 :class:`BufferedRandom` is capable of anything :class:`BufferedReader` or
552 :class:`BufferedWriter` can do.
553
554
555Text I/O
556--------
557
558.. class:: TextIOBase
559
560 Base class for text streams. This class provides a character and line based
561 interface to stream I/O. There is no :meth:`readinto` method because
562 Python's character strings are immutable. It inherits :class:`IOBase`.
563 There is no public constructor.
564
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000565 :class:`TextIOBase` provides or overrides these data attributes and
566 methods in addition to those from :class:`IOBase`:
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000567
568 .. attribute:: encoding
569
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000570 The name of the encoding used to decode the stream's bytes into
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000571 strings, and to encode strings into bytes.
572
573 .. attribute:: newlines
574
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000575 A string, a tuple of strings, or ``None``, indicating the newlines
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000576 translated so far.
577
578 .. method:: read(n)
579
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000580 Reads and returns at most *n* characters from the stream as a
581 single :class:`str`. If *n* is negative or ``None``, reads to EOF.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000582
583 .. method:: readline()
584
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000585 Reads until newline or EOF and returns a single :class:`str`. If
586 the stream is already at EOF, an empty string is returned.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000587
588 .. method:: write(s)
589
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000590 Writes the string *s* to the stream and returns the number of
591 characters written.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000592
593
594.. class:: TextIOWrapper(buffer[, encoding[, errors[, newline[, line_buffering]]]])
595
596 A buffered text stream over a :class:`BufferedIOBase` raw stream, *buffer*.
597 It inherits :class:`TextIOBase`.
598
599 *encoding* gives the name of the encoding that the stream will be decoded or
600 encoded with. It defaults to :func:`locale.getpreferredencoding`.
601
Benjamin Peterson53be57e2008-04-19 19:34:05 +0000602 *errors* is an optional string that specifies how encoding and decoding
603 errors are to be handled. Pass ``'strict'`` to raise a :exc:`ValueError`
604 exception if there is an encoding error (the default of ``None`` has the same
605 effect), or pass ``'ignore'`` to ignore errors. (Note that ignoring encoding
606 errors can lead to data loss.) ``'replace'`` causes a replacement marker
Benjamin Petersona7d09032008-04-19 19:47:34 +0000607 (such as ``'?'``) to be inserted where there is malformed data. When
608 writing, ``'xmlcharrefreplace'`` (replace with the appropriate XML character
609 reference) or ``'backslashreplace'`` (replace with backslashed escape
610 sequences) can be used. Any other error handling name that has been
611 registered with :func:`codecs.register_error` is also valid.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000612
613 *newline* can be ``None``, ``''``, ``'\n'``, ``'\r'``, or ``'\r\n'``. It
614 controls the handling of line endings. If it is ``None``, universal newlines
615 is enabled. With this enabled, on input, the lines endings ``'\n'``,
616 ``'\r'``, or ``'\r\n'`` are translated to ``'\n'`` before being returned to
617 the caller. Conversely, on output, ``'\n'`` is translated to the system
618 default line seperator, :data:`os.linesep`. If *newline* is any other of its
619 legal values, that newline becomes the newline when the file is read and it
620 is returned untranslated. On output, ``'\n'`` is converted to the *newline*.
621
622 If *line_buffering* is ``True``, :meth:`flush` is implied when a call to
623 write contains a newline character.
624
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000625 :class:`TextIOWrapper` provides these data attributes in addition to those of
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000626 :class:`TextIOBase` and its parents:
627
628 .. attribute:: errors
629
630 The encoding and decoding error setting.
631
632 .. attribute:: line_buffering
633
634 Whether line buffering is enabled.
635
636
637.. class:: StringIO([initial_value[, encoding[, errors[, newline]]]])
638
639 An in-memory stream for text. It in inherits :class:`TextIOWrapper`.
640
641 Create a new StringIO stream with an inital value, encoding, error handling,
642 and newline setting. See :class:`TextIOWrapper`\'s constructor for more
643 information.
644
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000645 :class:`StringIO` provides this method in addition to those from
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000646 :class:`TextIOWrapper` and its parents:
647
648 .. method:: getvalue()
649
Benjamin Petersonad9f6292008-04-21 11:57:40 +0000650 Returns a :class:`str` containing the entire contents of the buffer.
Benjamin Peterson7bb4d2d2008-04-13 02:01:27 +0000651
652
653.. class:: IncrementalNewlineDecoder
654
655 A helper codec that decodes newlines for universal newlines mode. It
656 inherits :class:`codecs.IncrementalDecoder`.
657