Debian Codegraph @

Doc/library/io.rst

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