1:mod:`io` --- Core tools for working with streams 2================================================= 3 4.. module:: io 5 :synopsis: Core tools for working with streams. 6 7.. moduleauthor:: Guido van Rossum <guido@python.org> 8.. moduleauthor:: Mike Verdone <mike.verdone@gmail.com> 9.. moduleauthor:: Mark Russell <mark.russell@zen.co.uk> 10.. moduleauthor:: Antoine Pitrou <solipsis@pitrou.net> 11.. moduleauthor:: Amaury Forgeot d'Arc <amauryfa@gmail.com> 12.. moduleauthor:: Benjamin Peterson <benjamin@python.org> 13.. sectionauthor:: Benjamin Peterson <benjamin@python.org> 14 15**Source code:** :source:`Lib/io.py` 16 17-------------- 18 19.. _io-overview: 20 21Overview 22-------- 23 24.. index:: 25 single: file object; io module 26 27The :mod:`io` module provides Python's main facilities for dealing with various 28types of I/O. There are three main types of I/O: *text I/O*, *binary I/O* 29and *raw I/O*. These are generic categories, and various backing stores can 30be used for each of them. A concrete object belonging to any of these 31categories is called a :term:`file object`. Other common terms are *stream* 32and *file-like object*. 33 34Independent of its category, each concrete stream object will also have 35various capabilities: it can be read-only, write-only, or read-write. It can 36also allow arbitrary random access (seeking forwards or backwards to any 37location), or only sequential access (for example in the case of a socket or 38pipe). 39 40All streams are careful about the type of data you give to them. For example 41giving a :class:`str` object to the ``write()`` method of a binary stream 42will raise a :exc:`TypeError`. So will giving a :class:`bytes` object to the 43``write()`` method of a text stream. 44 45.. versionchanged:: 3.3 46 Operations that used to raise :exc:`IOError` now raise :exc:`OSError`, since 47 :exc:`IOError` is now an alias of :exc:`OSError`. 48 49 50Text I/O 51^^^^^^^^ 52 53Text I/O expects and produces :class:`str` objects. This means that whenever 54the backing store is natively made of bytes (such as in the case of a file), 55encoding and decoding of data is made transparently as well as optional 56translation of platform-specific newline characters. 57 58The easiest way to create a text stream is with :meth:`open()`, optionally 59specifying an encoding:: 60 61 f = open("myfile.txt", "r", encoding="utf-8") 62 63In-memory text streams are also available as :class:`StringIO` objects:: 64 65 f = io.StringIO("some initial text data") 66 67The text stream API is described in detail in the documentation of 68:class:`TextIOBase`. 69 70 71Binary I/O 72^^^^^^^^^^ 73 74Binary I/O (also called *buffered I/O*) expects 75:term:`bytes-like objects <bytes-like object>` and produces :class:`bytes` 76objects. No encoding, decoding, or newline translation is performed. This 77category of streams can be used for all kinds of non-text data, and also when 78manual control over the handling of text data is desired. 79 80The easiest way to create a binary stream is with :meth:`open()` with ``'b'`` in 81the mode string:: 82 83 f = open("myfile.jpg", "rb") 84 85In-memory binary streams are also available as :class:`BytesIO` objects:: 86 87 f = io.BytesIO(b"some initial binary data: \x00\x01") 88 89The binary stream API is described in detail in the docs of 90:class:`BufferedIOBase`. 91 92Other library modules may provide additional ways to create text or binary 93streams. See :meth:`socket.socket.makefile` for example. 94 95 96Raw I/O 97^^^^^^^ 98 99Raw I/O (also called *unbuffered I/O*) is generally used as a low-level 100building-block for binary and text streams; it is rarely useful to directly 101manipulate a raw stream from user code. Nevertheless, you can create a raw 102stream by opening a file in binary mode with buffering disabled:: 103 104 f = open("myfile.jpg", "rb", buffering=0) 105 106The raw stream API is described in detail in the docs of :class:`RawIOBase`. 107 108 109High-level Module Interface 110--------------------------- 111 112.. data:: DEFAULT_BUFFER_SIZE 113 114 An int containing the default buffer size used by the module's buffered I/O 115 classes. :func:`open` uses the file's blksize (as obtained by 116 :func:`os.stat`) if possible. 117 118 119.. function:: open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) 120 121 This is an alias for the builtin :func:`open` function. 122 123 .. audit-event:: open path,mode,flags io.open 124 125 This function raises an :ref:`auditing event <auditing>` ``open`` with 126 arguments ``path``, ``mode`` and ``flags``. The ``mode`` and ``flags`` 127 arguments may have been modified or inferred from the original call. 128 129 130.. function:: open_code(path) 131 132 Opens the provided file with mode ``'rb'``. This function should be used 133 when the intent is to treat the contents as executable code. 134 135 ``path`` should be an absolute path. 136 137 The behavior of this function may be overridden by an earlier call to the 138 :c:func:`PyFile_SetOpenCodeHook`, however, it should always be considered 139 interchangeable with ``open(path, 'rb')``. Overriding the behavior is 140 intended for additional validation or preprocessing of the file. 141 142 .. versionadded:: 3.8 143 144 145.. exception:: BlockingIOError 146 147 This is a compatibility alias for the builtin :exc:`BlockingIOError` 148 exception. 149 150 151.. exception:: UnsupportedOperation 152 153 An exception inheriting :exc:`OSError` and :exc:`ValueError` that is raised 154 when an unsupported operation is called on a stream. 155 156 157In-memory streams 158^^^^^^^^^^^^^^^^^ 159 160It is also possible to use a :class:`str` or :term:`bytes-like object` as a 161file for both reading and writing. For strings :class:`StringIO` can be used 162like a file opened in text mode. :class:`BytesIO` can be used like a file 163opened in binary mode. Both provide full read-write capabilities with random 164access. 165 166 167.. seealso:: 168 169 :mod:`sys` 170 contains the standard IO streams: :data:`sys.stdin`, :data:`sys.stdout`, 171 and :data:`sys.stderr`. 172 173 174Class hierarchy 175--------------- 176 177The implementation of I/O streams is organized as a hierarchy of classes. First 178:term:`abstract base classes <abstract base class>` (ABCs), which are used to 179specify the various categories of streams, then concrete classes providing the 180standard stream implementations. 181 182 .. note:: 183 184 The abstract base classes also provide default implementations of some 185 methods in order to help implementation of concrete stream classes. For 186 example, :class:`BufferedIOBase` provides unoptimized implementations of 187 :meth:`~IOBase.readinto` and :meth:`~IOBase.readline`. 188 189At the top of the I/O hierarchy is the abstract base class :class:`IOBase`. It 190defines the basic interface to a stream. Note, however, that there is no 191separation between reading and writing to streams; implementations are allowed 192to raise :exc:`UnsupportedOperation` if they do not support a given operation. 193 194The :class:`RawIOBase` ABC extends :class:`IOBase`. It deals with the reading 195and writing of bytes to a stream. :class:`FileIO` subclasses :class:`RawIOBase` 196to provide an interface to files in the machine's file system. 197 198The :class:`BufferedIOBase` ABC deals with buffering on a raw byte stream 199(:class:`RawIOBase`). Its subclasses, :class:`BufferedWriter`, 200:class:`BufferedReader`, and :class:`BufferedRWPair` buffer streams that are 201readable, writable, and both readable and writable. :class:`BufferedRandom` 202provides a buffered interface to random access streams. Another 203:class:`BufferedIOBase` subclass, :class:`BytesIO`, is a stream of in-memory 204bytes. 205 206The :class:`TextIOBase` ABC, another subclass of :class:`IOBase`, deals with 207streams whose bytes represent text, and handles encoding and decoding to and 208from strings. :class:`TextIOWrapper`, which extends it, is a buffered text 209interface to a buffered raw stream (:class:`BufferedIOBase`). Finally, 210:class:`StringIO` is an in-memory stream for text. 211 212Argument names are not part of the specification, and only the arguments of 213:func:`open` are intended to be used as keyword arguments. 214 215The following table summarizes the ABCs provided by the :mod:`io` module: 216 217.. tabularcolumns:: |l|l|L|L| 218 219========================= ================== ======================== ================================================== 220ABC Inherits Stub Methods Mixin Methods and Properties 221========================= ================== ======================== ================================================== 222:class:`IOBase` ``fileno``, ``seek``, ``close``, ``closed``, ``__enter__``, 223 and ``truncate`` ``__exit__``, ``flush``, ``isatty``, ``__iter__``, 224 ``__next__``, ``readable``, ``readline``, 225 ``readlines``, ``seekable``, ``tell``, 226 ``writable``, and ``writelines`` 227:class:`RawIOBase` :class:`IOBase` ``readinto`` and Inherited :class:`IOBase` methods, ``read``, 228 ``write`` and ``readall`` 229:class:`BufferedIOBase` :class:`IOBase` ``detach``, ``read``, Inherited :class:`IOBase` methods, ``readinto``, 230 ``read1``, and ``write`` and ``readinto1`` 231:class:`TextIOBase` :class:`IOBase` ``detach``, ``read``, Inherited :class:`IOBase` methods, ``encoding``, 232 ``readline``, and ``errors``, and ``newlines`` 233 ``write`` 234========================= ================== ======================== ================================================== 235 236 237I/O Base Classes 238^^^^^^^^^^^^^^^^ 239 240.. class:: IOBase 241 242 The abstract base class for all I/O classes, acting on streams of bytes. 243 There is no public constructor. 244 245 This class provides empty abstract implementations for many methods 246 that derived classes can override selectively; the default 247 implementations represent a file that cannot be read, written or 248 seeked. 249 250 Even though :class:`IOBase` does not declare :meth:`read` 251 or :meth:`write` because their signatures will vary, implementations and 252 clients should consider those methods part of the interface. Also, 253 implementations may raise a :exc:`ValueError` (or :exc:`UnsupportedOperation`) 254 when operations they do not support are called. 255 256 The basic type used for binary data read from or written to a file is 257 :class:`bytes`. Other :term:`bytes-like objects <bytes-like object>` are 258 accepted as method arguments too. Text I/O classes work with :class:`str` data. 259 260 Note that calling any method (even inquiries) on a closed stream is 261 undefined. Implementations may raise :exc:`ValueError` in this case. 262 263 :class:`IOBase` (and its subclasses) supports the iterator protocol, meaning 264 that an :class:`IOBase` object can be iterated over yielding the lines in a 265 stream. Lines are defined slightly differently depending on whether the 266 stream is a binary stream (yielding bytes), or a text stream (yielding 267 character strings). See :meth:`~IOBase.readline` below. 268 269 :class:`IOBase` is also a context manager and therefore supports the 270 :keyword:`with` statement. In this example, *file* is closed after the 271 :keyword:`!with` statement's suite is finished---even if an exception occurs:: 272 273 with open('spam.txt', 'w') as file: 274 file.write('Spam and eggs!') 275 276 :class:`IOBase` provides these data attributes and methods: 277 278 .. method:: close() 279 280 Flush and close this stream. This method has no effect if the file is 281 already closed. Once the file is closed, any operation on the file 282 (e.g. reading or writing) will raise a :exc:`ValueError`. 283 284 As a convenience, it is allowed to call this method more than once; 285 only the first call, however, will have an effect. 286 287 .. attribute:: closed 288 289 ``True`` if the stream is closed. 290 291 .. method:: fileno() 292 293 Return the underlying file descriptor (an integer) of the stream if it 294 exists. An :exc:`OSError` is raised if the IO object does not use a file 295 descriptor. 296 297 .. method:: flush() 298 299 Flush the write buffers of the stream if applicable. This does nothing 300 for read-only and non-blocking streams. 301 302 .. method:: isatty() 303 304 Return ``True`` if the stream is interactive (i.e., connected to 305 a terminal/tty device). 306 307 .. method:: readable() 308 309 Return ``True`` if the stream can be read from. If ``False``, :meth:`read` 310 will raise :exc:`OSError`. 311 312 .. method:: readline(size=-1) 313 314 Read and return one line from the stream. If *size* is specified, at 315 most *size* bytes will be read. 316 317 The line terminator is always ``b'\n'`` for binary files; for text files, 318 the *newline* argument to :func:`open` can be used to select the line 319 terminator(s) recognized. 320 321 .. method:: readlines(hint=-1) 322 323 Read and return a list of lines from the stream. *hint* can be specified 324 to control the number of lines read: no more lines will be read if the 325 total size (in bytes/characters) of all lines so far exceeds *hint*. 326 327 Note that it's already possible to iterate on file objects using ``for 328 line in file: ...`` without calling ``file.readlines()``. 329 330 .. method:: seek(offset, whence=SEEK_SET) 331 332 Change the stream position to the given byte *offset*. *offset* is 333 interpreted relative to the position indicated by *whence*. The default 334 value for *whence* is :data:`SEEK_SET`. Values for *whence* are: 335 336 * :data:`SEEK_SET` or ``0`` -- start of the stream (the default); 337 *offset* should be zero or positive 338 * :data:`SEEK_CUR` or ``1`` -- current stream position; *offset* may 339 be negative 340 * :data:`SEEK_END` or ``2`` -- end of the stream; *offset* is usually 341 negative 342 343 Return the new absolute position. 344 345 .. versionadded:: 3.1 346 The ``SEEK_*`` constants. 347 348 .. versionadded:: 3.3 349 Some operating systems could support additional values, like 350 :data:`os.SEEK_HOLE` or :data:`os.SEEK_DATA`. The valid values 351 for a file could depend on it being open in text or binary mode. 352 353 .. method:: seekable() 354 355 Return ``True`` if the stream supports random access. If ``False``, 356 :meth:`seek`, :meth:`tell` and :meth:`truncate` will raise :exc:`OSError`. 357 358 .. method:: tell() 359 360 Return the current stream position. 361 362 .. method:: truncate(size=None) 363 364 Resize the stream to the given *size* in bytes (or the current position 365 if *size* is not specified). The current stream position isn't changed. 366 This resizing can extend or reduce the current file size. In case of 367 extension, the contents of the new file area depend on the platform 368 (on most systems, additional bytes are zero-filled). The new file size 369 is returned. 370 371 .. versionchanged:: 3.5 372 Windows will now zero-fill files when extending. 373 374 .. method:: writable() 375 376 Return ``True`` if the stream supports writing. If ``False``, 377 :meth:`write` and :meth:`truncate` will raise :exc:`OSError`. 378 379 .. method:: writelines(lines) 380 381 Write a list of lines to the stream. Line separators are not added, so it 382 is usual for each of the lines provided to have a line separator at the 383 end. 384 385 .. method:: __del__() 386 387 Prepare for object destruction. :class:`IOBase` provides a default 388 implementation of this method that calls the instance's 389 :meth:`~IOBase.close` method. 390 391 392.. class:: RawIOBase 393 394 Base class for raw binary I/O. It inherits :class:`IOBase`. There is no 395 public constructor. 396 397 Raw binary I/O typically provides low-level access to an underlying OS 398 device or API, and does not try to encapsulate it in high-level primitives 399 (this is left to Buffered I/O and Text I/O, described later in this page). 400 401 In addition to the attributes and methods from :class:`IOBase`, 402 :class:`RawIOBase` provides the following methods: 403 404 .. method:: read(size=-1) 405 406 Read up to *size* bytes from the object and return them. As a convenience, 407 if *size* is unspecified or -1, all bytes until EOF are returned. 408 Otherwise, only one system call is ever made. Fewer than *size* bytes may 409 be returned if the operating system call returns fewer than *size* bytes. 410 411 If 0 bytes are returned, and *size* was not 0, this indicates end of file. 412 If the object is in non-blocking mode and no bytes are available, 413 ``None`` is returned. 414 415 The default implementation defers to :meth:`readall` and 416 :meth:`readinto`. 417 418 .. method:: readall() 419 420 Read and return all the bytes from the stream until EOF, using multiple 421 calls to the stream if necessary. 422 423 .. method:: readinto(b) 424 425 Read bytes into a pre-allocated, writable 426 :term:`bytes-like object` *b*, and return the 427 number of bytes read. For example, *b* might be a :class:`bytearray`. 428 If the object is in non-blocking mode and no bytes 429 are available, ``None`` is returned. 430 431 .. method:: write(b) 432 433 Write the given :term:`bytes-like object`, *b*, to the 434 underlying raw stream, and return the number of 435 bytes written. This can be less than the length of *b* in 436 bytes, depending on specifics of the underlying raw 437 stream, and especially if it is in non-blocking mode. ``None`` is 438 returned if the raw stream is set not to block and no single byte could 439 be readily written to it. The caller may release or mutate *b* after 440 this method returns, so the implementation should only access *b* 441 during the method call. 442 443 444.. class:: BufferedIOBase 445 446 Base class for binary streams that support some kind of buffering. 447 It inherits :class:`IOBase`. There is no public constructor. 448 449 The main difference with :class:`RawIOBase` is that methods :meth:`read`, 450 :meth:`readinto` and :meth:`write` will try (respectively) to read as much 451 input as requested or to consume all given output, at the expense of 452 making perhaps more than one system call. 453 454 In addition, those methods can raise :exc:`BlockingIOError` if the 455 underlying raw stream is in non-blocking mode and cannot take or give 456 enough data; unlike their :class:`RawIOBase` counterparts, they will 457 never return ``None``. 458 459 Besides, the :meth:`read` method does not have a default 460 implementation that defers to :meth:`readinto`. 461 462 A typical :class:`BufferedIOBase` implementation should not inherit from a 463 :class:`RawIOBase` implementation, but wrap one, like 464 :class:`BufferedWriter` and :class:`BufferedReader` do. 465 466 :class:`BufferedIOBase` provides or overrides these methods and attribute in 467 addition to those from :class:`IOBase`: 468 469 .. attribute:: raw 470 471 The underlying raw stream (a :class:`RawIOBase` instance) that 472 :class:`BufferedIOBase` deals with. This is not part of the 473 :class:`BufferedIOBase` API and may not exist on some implementations. 474 475 .. method:: detach() 476 477 Separate the underlying raw stream from the buffer and return it. 478 479 After the raw stream has been detached, the buffer is in an unusable 480 state. 481 482 Some buffers, like :class:`BytesIO`, do not have the concept of a single 483 raw stream to return from this method. They raise 484 :exc:`UnsupportedOperation`. 485 486 .. versionadded:: 3.1 487 488 .. method:: read(size=-1) 489 490 Read and return up to *size* bytes. If the argument is omitted, ``None``, 491 or negative, data is read and returned until EOF is reached. An empty 492 :class:`bytes` object is returned if the stream is already at EOF. 493 494 If the argument is positive, and the underlying raw stream is not 495 interactive, multiple raw reads may be issued to satisfy the byte count 496 (unless EOF is reached first). But for interactive raw streams, at most 497 one raw read will be issued, and a short result does not imply that EOF is 498 imminent. 499 500 A :exc:`BlockingIOError` is raised if the underlying raw stream is in 501 non blocking-mode, and has no data available at the moment. 502 503 .. method:: read1([size]) 504 505 Read and return up to *size* bytes, with at most one call to the 506 underlying raw stream's :meth:`~RawIOBase.read` (or 507 :meth:`~RawIOBase.readinto`) method. This can be useful if you are 508 implementing your own buffering on top of a :class:`BufferedIOBase` 509 object. 510 511 If *size* is ``-1`` (the default), an arbitrary number of bytes are 512 returned (more than zero unless EOF is reached). 513 514 .. method:: readinto(b) 515 516 Read bytes into a pre-allocated, writable 517 :term:`bytes-like object` *b* and return the number of bytes read. 518 For example, *b* might be a :class:`bytearray`. 519 520 Like :meth:`read`, multiple reads may be issued to the underlying raw 521 stream, unless the latter is interactive. 522 523 A :exc:`BlockingIOError` is raised if the underlying raw stream is in non 524 blocking-mode, and has no data available at the moment. 525 526 .. method:: readinto1(b) 527 528 Read bytes into a pre-allocated, writable 529 :term:`bytes-like object` *b*, using at most one call to 530 the underlying raw stream's :meth:`~RawIOBase.read` (or 531 :meth:`~RawIOBase.readinto`) method. Return the number of bytes read. 532 533 A :exc:`BlockingIOError` is raised if the underlying raw stream is in non 534 blocking-mode, and has no data available at the moment. 535 536 .. versionadded:: 3.5 537 538 .. method:: write(b) 539 540 Write the given :term:`bytes-like object`, *b*, and return the number 541 of bytes written (always equal to the length of *b* in bytes, since if 542 the write fails an :exc:`OSError` will be raised). Depending on the 543 actual implementation, these bytes may be readily written to the 544 underlying stream, or held in a buffer for performance and latency 545 reasons. 546 547 When in non-blocking mode, a :exc:`BlockingIOError` is raised if the 548 data needed to be written to the raw stream but it couldn't accept 549 all the data without blocking. 550 551 The caller may release or mutate *b* after this method returns, 552 so the implementation should only access *b* during the method call. 553 554 555Raw File I/O 556^^^^^^^^^^^^ 557 558.. class:: FileIO(name, mode='r', closefd=True, opener=None) 559 560 :class:`FileIO` represents an OS-level file containing bytes data. 561 It implements the :class:`RawIOBase` interface (and therefore the 562 :class:`IOBase` interface, too). 563 564 The *name* can be one of two things: 565 566 * a character string or :class:`bytes` object representing the path to the 567 file which will be opened. In this case closefd must be ``True`` (the default) 568 otherwise an error will be raised. 569 * an integer representing the number of an existing OS-level file descriptor 570 to which the resulting :class:`FileIO` object will give access. When the 571 FileIO object is closed this fd will be closed as well, unless *closefd* 572 is set to ``False``. 573 574 The *mode* can be ``'r'``, ``'w'``, ``'x'`` or ``'a'`` for reading 575 (default), writing, exclusive creation or appending. The file will be 576 created if it doesn't exist when opened for writing or appending; it will be 577 truncated when opened for writing. :exc:`FileExistsError` will be raised if 578 it already exists when opened for creating. Opening a file for creating 579 implies writing, so this mode behaves in a similar way to ``'w'``. Add a 580 ``'+'`` to the mode to allow simultaneous reading and writing. 581 582 The :meth:`read` (when called with a positive argument), :meth:`readinto` 583 and :meth:`write` methods on this class will only make one system call. 584 585 A custom opener can be used by passing a callable as *opener*. The underlying 586 file descriptor for the file object is then obtained by calling *opener* with 587 (*name*, *flags*). *opener* must return an open file descriptor (passing 588 :mod:`os.open` as *opener* results in functionality similar to passing 589 ``None``). 590 591 The newly created file is :ref:`non-inheritable <fd_inheritance>`. 592 593 See the :func:`open` built-in function for examples on using the *opener* 594 parameter. 595 596 .. versionchanged:: 3.3 597 The *opener* parameter was added. 598 The ``'x'`` mode was added. 599 600 .. versionchanged:: 3.4 601 The file is now non-inheritable. 602 603 In addition to the attributes and methods from :class:`IOBase` and 604 :class:`RawIOBase`, :class:`FileIO` provides the following data 605 attributes: 606 607 .. attribute:: mode 608 609 The mode as given in the constructor. 610 611 .. attribute:: name 612 613 The file name. This is the file descriptor of the file when no name is 614 given in the constructor. 615 616 617Buffered Streams 618^^^^^^^^^^^^^^^^ 619 620Buffered I/O streams provide a higher-level interface to an I/O device 621than raw I/O does. 622 623.. class:: BytesIO([initial_bytes]) 624 625 A stream implementation using an in-memory bytes buffer. It inherits 626 :class:`BufferedIOBase`. The buffer is discarded when the 627 :meth:`~IOBase.close` method is called. 628 629 The optional argument *initial_bytes* is a :term:`bytes-like object` that 630 contains initial data. 631 632 :class:`BytesIO` provides or overrides these methods in addition to those 633 from :class:`BufferedIOBase` and :class:`IOBase`: 634 635 .. method:: getbuffer() 636 637 Return a readable and writable view over the contents of the buffer 638 without copying them. Also, mutating the view will transparently 639 update the contents of the buffer:: 640 641 >>> b = io.BytesIO(b"abcdef") 642 >>> view = b.getbuffer() 643 >>> view[2:4] = b"56" 644 >>> b.getvalue() 645 b'ab56ef' 646 647 .. note:: 648 As long as the view exists, the :class:`BytesIO` object cannot be 649 resized or closed. 650 651 .. versionadded:: 3.2 652 653 .. method:: getvalue() 654 655 Return :class:`bytes` containing the entire contents of the buffer. 656 657 658 .. method:: read1([size]) 659 660 In :class:`BytesIO`, this is the same as :meth:`~BufferedIOBase.read`. 661 662 .. versionchanged:: 3.7 663 The *size* argument is now optional. 664 665 .. method:: readinto1(b) 666 667 In :class:`BytesIO`, this is the same as :meth:`~BufferedIOBase.readinto`. 668 669 .. versionadded:: 3.5 670 671.. class:: BufferedReader(raw, buffer_size=DEFAULT_BUFFER_SIZE) 672 673 A buffer providing higher-level access to a readable, sequential 674 :class:`RawIOBase` object. It inherits :class:`BufferedIOBase`. 675 When reading data from this object, a larger amount of data may be 676 requested from the underlying raw stream, and kept in an internal buffer. 677 The buffered data can then be returned directly on subsequent reads. 678 679 The constructor creates a :class:`BufferedReader` for the given readable 680 *raw* stream and *buffer_size*. If *buffer_size* is omitted, 681 :data:`DEFAULT_BUFFER_SIZE` is used. 682 683 :class:`BufferedReader` provides or overrides these methods in addition to 684 those from :class:`BufferedIOBase` and :class:`IOBase`: 685 686 .. method:: peek([size]) 687 688 Return bytes from the stream without advancing the position. At most one 689 single read on the raw stream is done to satisfy the call. The number of 690 bytes returned may be less or more than requested. 691 692 .. method:: read([size]) 693 694 Read and return *size* bytes, or if *size* is not given or negative, until 695 EOF or if the read call would block in non-blocking mode. 696 697 .. method:: read1([size]) 698 699 Read and return up to *size* bytes with only one call on the raw stream. 700 If at least one byte is buffered, only buffered bytes are returned. 701 Otherwise, one raw stream read call is made. 702 703 .. versionchanged:: 3.7 704 The *size* argument is now optional. 705 706 707.. class:: BufferedWriter(raw, buffer_size=DEFAULT_BUFFER_SIZE) 708 709 A buffer providing higher-level access to a writeable, sequential 710 :class:`RawIOBase` object. It inherits :class:`BufferedIOBase`. 711 When writing to this object, data is normally placed into an internal 712 buffer. The buffer will be written out to the underlying :class:`RawIOBase` 713 object under various conditions, including: 714 715 * when the buffer gets too small for all pending data; 716 * when :meth:`flush()` is called; 717 * when a :meth:`seek()` is requested (for :class:`BufferedRandom` objects); 718 * when the :class:`BufferedWriter` object is closed or destroyed. 719 720 The constructor creates a :class:`BufferedWriter` for the given writeable 721 *raw* stream. If the *buffer_size* is not given, it defaults to 722 :data:`DEFAULT_BUFFER_SIZE`. 723 724 :class:`BufferedWriter` provides or overrides these methods in addition to 725 those from :class:`BufferedIOBase` and :class:`IOBase`: 726 727 .. method:: flush() 728 729 Force bytes held in the buffer into the raw stream. A 730 :exc:`BlockingIOError` should be raised if the raw stream blocks. 731 732 .. method:: write(b) 733 734 Write the :term:`bytes-like object`, *b*, and return the 735 number of bytes written. When in non-blocking mode, a 736 :exc:`BlockingIOError` is raised if the buffer needs to be written out but 737 the raw stream blocks. 738 739 740.. class:: BufferedRandom(raw, buffer_size=DEFAULT_BUFFER_SIZE) 741 742 A buffered interface to random access streams. It inherits 743 :class:`BufferedReader` and :class:`BufferedWriter`. 744 745 The constructor creates a reader and writer for a seekable raw stream, given 746 in the first argument. If the *buffer_size* is omitted it defaults to 747 :data:`DEFAULT_BUFFER_SIZE`. 748 749 :class:`BufferedRandom` is capable of anything :class:`BufferedReader` or 750 :class:`BufferedWriter` can do. In addition, :meth:`seek` and :meth:`tell` 751 are guaranteed to be implemented. 752 753 754.. class:: BufferedRWPair(reader, writer, buffer_size=DEFAULT_BUFFER_SIZE) 755 756 A buffered I/O object combining two unidirectional :class:`RawIOBase` 757 objects -- one readable, the other writeable -- into a single bidirectional 758 endpoint. It inherits :class:`BufferedIOBase`. 759 760 *reader* and *writer* are :class:`RawIOBase` objects that are readable and 761 writeable respectively. If the *buffer_size* is omitted it defaults to 762 :data:`DEFAULT_BUFFER_SIZE`. 763 764 :class:`BufferedRWPair` implements all of :class:`BufferedIOBase`\'s methods 765 except for :meth:`~BufferedIOBase.detach`, which raises 766 :exc:`UnsupportedOperation`. 767 768 .. warning:: 769 770 :class:`BufferedRWPair` does not attempt to synchronize accesses to 771 its underlying raw streams. You should not pass it the same object 772 as reader and writer; use :class:`BufferedRandom` instead. 773 774 775Text I/O 776^^^^^^^^ 777 778.. class:: TextIOBase 779 780 Base class for text streams. This class provides a character and line based 781 interface to stream I/O. It inherits :class:`IOBase`. 782 There is no public constructor. 783 784 :class:`TextIOBase` provides or overrides these data attributes and 785 methods in addition to those from :class:`IOBase`: 786 787 .. attribute:: encoding 788 789 The name of the encoding used to decode the stream's bytes into 790 strings, and to encode strings into bytes. 791 792 .. attribute:: errors 793 794 The error setting of the decoder or encoder. 795 796 .. attribute:: newlines 797 798 A string, a tuple of strings, or ``None``, indicating the newlines 799 translated so far. Depending on the implementation and the initial 800 constructor flags, this may not be available. 801 802 .. attribute:: buffer 803 804 The underlying binary buffer (a :class:`BufferedIOBase` instance) that 805 :class:`TextIOBase` deals with. This is not part of the 806 :class:`TextIOBase` API and may not exist in some implementations. 807 808 .. method:: detach() 809 810 Separate the underlying binary buffer from the :class:`TextIOBase` and 811 return it. 812 813 After the underlying buffer has been detached, the :class:`TextIOBase` is 814 in an unusable state. 815 816 Some :class:`TextIOBase` implementations, like :class:`StringIO`, may not 817 have the concept of an underlying buffer and calling this method will 818 raise :exc:`UnsupportedOperation`. 819 820 .. versionadded:: 3.1 821 822 .. method:: read(size=-1) 823 824 Read and return at most *size* characters from the stream as a single 825 :class:`str`. If *size* is negative or ``None``, reads until EOF. 826 827 .. method:: readline(size=-1) 828 829 Read until newline or EOF and return a single ``str``. If the stream is 830 already at EOF, an empty string is returned. 831 832 If *size* is specified, at most *size* characters will be read. 833 834 .. method:: seek(offset, whence=SEEK_SET) 835 836 Change the stream position to the given *offset*. Behaviour depends on 837 the *whence* parameter. The default value for *whence* is 838 :data:`SEEK_SET`. 839 840 * :data:`SEEK_SET` or ``0``: seek from the start of the stream 841 (the default); *offset* must either be a number returned by 842 :meth:`TextIOBase.tell`, or zero. Any other *offset* value 843 produces undefined behaviour. 844 * :data:`SEEK_CUR` or ``1``: "seek" to the current position; 845 *offset* must be zero, which is a no-operation (all other values 846 are unsupported). 847 * :data:`SEEK_END` or ``2``: seek to the end of the stream; 848 *offset* must be zero (all other values are unsupported). 849 850 Return the new absolute position as an opaque number. 851 852 .. versionadded:: 3.1 853 The ``SEEK_*`` constants. 854 855 .. method:: tell() 856 857 Return the current stream position as an opaque number. The number 858 does not usually represent a number of bytes in the underlying 859 binary storage. 860 861 .. method:: write(s) 862 863 Write the string *s* to the stream and return the number of characters 864 written. 865 866 867.. class:: TextIOWrapper(buffer, encoding=None, errors=None, newline=None, \ 868 line_buffering=False, write_through=False) 869 870 A buffered text stream over a :class:`BufferedIOBase` binary stream. 871 It inherits :class:`TextIOBase`. 872 873 *encoding* gives the name of the encoding that the stream will be decoded or 874 encoded with. It defaults to 875 :func:`locale.getpreferredencoding(False) <locale.getpreferredencoding>`. 876 877 *errors* is an optional string that specifies how encoding and decoding 878 errors are to be handled. Pass ``'strict'`` to raise a :exc:`ValueError` 879 exception if there is an encoding error (the default of ``None`` has the same 880 effect), or pass ``'ignore'`` to ignore errors. (Note that ignoring encoding 881 errors can lead to data loss.) ``'replace'`` causes a replacement marker 882 (such as ``'?'``) to be inserted where there is malformed data. 883 ``'backslashreplace'`` causes malformed data to be replaced by a 884 backslashed escape sequence. When writing, ``'xmlcharrefreplace'`` 885 (replace with the appropriate XML character reference) or ``'namereplace'`` 886 (replace with ``\N{...}`` escape sequences) can be used. Any other error 887 handling name that has been registered with 888 :func:`codecs.register_error` is also valid. 889 890 .. index:: 891 single: universal newlines; io.TextIOWrapper class 892 893 *newline* controls how line endings are handled. It can be ``None``, 894 ``''``, ``'\n'``, ``'\r'``, and ``'\r\n'``. It works as follows: 895 896 * When reading input from the stream, if *newline* is ``None``, 897 :term:`universal newlines` mode is enabled. Lines in the input can end in 898 ``'\n'``, ``'\r'``, or ``'\r\n'``, and these are translated into ``'\n'`` 899 before being returned to the caller. If it is ``''``, universal newlines 900 mode is enabled, but line endings are returned to the caller untranslated. 901 If it has any of the other legal values, input lines are only terminated 902 by the given string, and the line ending is returned to the caller 903 untranslated. 904 905 * When writing output to the stream, if *newline* is ``None``, any ``'\n'`` 906 characters written are translated to the system default line separator, 907 :data:`os.linesep`. If *newline* is ``''`` or ``'\n'``, no translation 908 takes place. If *newline* is any of the other legal values, any ``'\n'`` 909 characters written are translated to the given string. 910 911 If *line_buffering* is ``True``, :meth:`flush` is implied when a call to 912 write contains a newline character or a carriage return. 913 914 If *write_through* is ``True``, calls to :meth:`write` are guaranteed 915 not to be buffered: any data written on the :class:`TextIOWrapper` 916 object is immediately handled to its underlying binary *buffer*. 917 918 .. versionchanged:: 3.3 919 The *write_through* argument has been added. 920 921 .. versionchanged:: 3.3 922 The default *encoding* is now ``locale.getpreferredencoding(False)`` 923 instead of ``locale.getpreferredencoding()``. Don't change temporary the 924 locale encoding using :func:`locale.setlocale`, use the current locale 925 encoding instead of the user preferred encoding. 926 927 :class:`TextIOWrapper` provides these members in addition to those of 928 :class:`TextIOBase` and its parents: 929 930 .. attribute:: line_buffering 931 932 Whether line buffering is enabled. 933 934 .. attribute:: write_through 935 936 Whether writes are passed immediately to the underlying binary 937 buffer. 938 939 .. versionadded:: 3.7 940 941 .. method:: reconfigure(*[, encoding][, errors][, newline][, \ 942 line_buffering][, write_through]) 943 944 Reconfigure this text stream using new settings for *encoding*, 945 *errors*, *newline*, *line_buffering* and *write_through*. 946 947 Parameters not specified keep current settings, except 948 ``errors='strict'`` is used when *encoding* is specified but 949 *errors* is not specified. 950 951 It is not possible to change the encoding or newline if some data 952 has already been read from the stream. On the other hand, changing 953 encoding after write is possible. 954 955 This method does an implicit stream flush before setting the 956 new parameters. 957 958 .. versionadded:: 3.7 959 960 961.. class:: StringIO(initial_value='', newline='\\n') 962 963 An in-memory stream for text I/O. The text buffer is discarded when the 964 :meth:`~IOBase.close` method is called. 965 966 The initial value of the buffer can be set by providing *initial_value*. 967 If newline translation is enabled, newlines will be encoded as if by 968 :meth:`~TextIOBase.write`. The stream is positioned at the start of 969 the buffer. 970 971 The *newline* argument works like that of :class:`TextIOWrapper`. 972 The default is to consider only ``\n`` characters as ends of lines and 973 to do no newline translation. If *newline* is set to ``None``, 974 newlines are written as ``\n`` on all platforms, but universal 975 newline decoding is still performed when reading. 976 977 :class:`StringIO` provides this method in addition to those from 978 :class:`TextIOBase` and its parents: 979 980 .. method:: getvalue() 981 982 Return a ``str`` containing the entire contents of the buffer. 983 Newlines are decoded as if by :meth:`~TextIOBase.read`, although 984 the stream position is not changed. 985 986 Example usage:: 987 988 import io 989 990 output = io.StringIO() 991 output.write('First line.\n') 992 print('Second line.', file=output) 993 994 # Retrieve file contents -- this will be 995 # 'First line.\nSecond line.\n' 996 contents = output.getvalue() 997 998 # Close object and discard memory buffer -- 999 # .getvalue() will now raise an exception. 1000 output.close() 1001 1002 1003.. index:: 1004 single: universal newlines; io.IncrementalNewlineDecoder class 1005 1006.. class:: IncrementalNewlineDecoder 1007 1008 A helper codec that decodes newlines for :term:`universal newlines` mode. 1009 It inherits :class:`codecs.IncrementalDecoder`. 1010 1011 1012Performance 1013----------- 1014 1015This section discusses the performance of the provided concrete I/O 1016implementations. 1017 1018Binary I/O 1019^^^^^^^^^^ 1020 1021By reading and writing only large chunks of data even when the user asks for a 1022single byte, buffered I/O hides any inefficiency in calling and executing the 1023operating system's unbuffered I/O routines. The gain depends on the OS and the 1024kind of I/O which is performed. For example, on some modern OSes such as Linux, 1025unbuffered disk I/O can be as fast as buffered I/O. The bottom line, however, 1026is that buffered I/O offers predictable performance regardless of the platform 1027and the backing device. Therefore, it is almost always preferable to use 1028buffered I/O rather than unbuffered I/O for binary data. 1029 1030Text I/O 1031^^^^^^^^ 1032 1033Text I/O over a binary storage (such as a file) is significantly slower than 1034binary I/O over the same storage, because it requires conversions between 1035unicode and binary data using a character codec. This can become noticeable 1036handling huge amounts of text data like large log files. Also, 1037:meth:`TextIOWrapper.tell` and :meth:`TextIOWrapper.seek` are both quite slow 1038due to the reconstruction algorithm used. 1039 1040:class:`StringIO`, however, is a native in-memory unicode container and will 1041exhibit similar speed to :class:`BytesIO`. 1042 1043Multi-threading 1044^^^^^^^^^^^^^^^ 1045 1046:class:`FileIO` objects are thread-safe to the extent that the operating system 1047calls (such as ``read(2)`` under Unix) they wrap are thread-safe too. 1048 1049Binary buffered objects (instances of :class:`BufferedReader`, 1050:class:`BufferedWriter`, :class:`BufferedRandom` and :class:`BufferedRWPair`) 1051protect their internal structures using a lock; it is therefore safe to call 1052them from multiple threads at once. 1053 1054:class:`TextIOWrapper` objects are not thread-safe. 1055 1056Reentrancy 1057^^^^^^^^^^ 1058 1059Binary buffered objects (instances of :class:`BufferedReader`, 1060:class:`BufferedWriter`, :class:`BufferedRandom` and :class:`BufferedRWPair`) 1061are not reentrant. While reentrant calls will not happen in normal situations, 1062they can arise from doing I/O in a :mod:`signal` handler. If a thread tries to 1063re-enter a buffered object which it is already accessing, a :exc:`RuntimeError` 1064is raised. Note this doesn't prohibit a different thread from entering the 1065buffered object. 1066 1067The above implicitly extends to text files, since the :func:`open()` function 1068will wrap a buffered object inside a :class:`TextIOWrapper`. This includes 1069standard streams and therefore affects the built-in function :func:`print()` as 1070well. 1071