summaryrefslogtreecommitdiff
path: root/devdocs/python~3.12/library%2Fio.html
blob: bfa8c0a59fd906294c8fa5642eb7be189eb29cf1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
 <span id="io-core-tools-for-working-with-streams"></span><h1>io — Core tools for working with streams</h1> <p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/io.py">Lib/io.py</a></p>  <section id="overview"> <span id="io-overview"></span><h2>Overview</h2> <p id="index-0">The <a class="reference internal" href="#module-io" title="io: Core tools for working with streams."><code>io</code></a> module provides Python’s main facilities for dealing with various types of I/O. There are three main types of I/O: <em>text I/O</em>, <em>binary I/O</em> and <em>raw I/O</em>. These are generic categories, and various backing stores can be used for each of them. A concrete object belonging to any of these categories is called a <a class="reference internal" href="../glossary#term-file-object"><span class="xref std std-term">file object</span></a>. Other common terms are <em>stream</em> and <em>file-like object</em>.</p> <p>Independent of its category, each concrete stream object will also have various capabilities: it can be read-only, write-only, or read-write. It can also allow arbitrary random access (seeking forwards or backwards to any location), or only sequential access (for example in the case of a socket or pipe).</p> <p>All streams are careful about the type of data you give to them. For example giving a <a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a> object to the <code>write()</code> method of a binary stream will raise a <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a>. So will giving a <a class="reference internal" href="stdtypes#bytes" title="bytes"><code>bytes</code></a> object to the <code>write()</code> method of a text stream.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.3: </span>Operations that used to raise <a class="reference internal" href="exceptions#IOError" title="IOError"><code>IOError</code></a> now raise <a class="reference internal" href="exceptions#OSError" title="OSError"><code>OSError</code></a>, since <a class="reference internal" href="exceptions#IOError" title="IOError"><code>IOError</code></a> is now an alias of <a class="reference internal" href="exceptions#OSError" title="OSError"><code>OSError</code></a>.</p> </div> <section id="text-i-o"> <h3>Text I/O</h3> <p>Text I/O expects and produces <a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a> objects. This means that whenever the backing store is natively made of bytes (such as in the case of a file), encoding and decoding of data is made transparently as well as optional translation of platform-specific newline characters.</p> <p>The easiest way to create a text stream is with <a class="reference internal" href="functions#open" title="open"><code>open()</code></a>, optionally specifying an encoding:</p> <pre data-language="python">f = open("myfile.txt", "r", encoding="utf-8")
</pre> <p>In-memory text streams are also available as <a class="reference internal" href="#io.StringIO" title="io.StringIO"><code>StringIO</code></a> objects:</p> <pre data-language="python">f = io.StringIO("some initial text data")
</pre> <p>The text stream API is described in detail in the documentation of <a class="reference internal" href="#io.TextIOBase" title="io.TextIOBase"><code>TextIOBase</code></a>.</p> </section> <section id="binary-i-o"> <h3>Binary I/O</h3> <p>Binary I/O (also called <em>buffered I/O</em>) expects <a class="reference internal" href="../glossary#term-bytes-like-object"><span class="xref std std-term">bytes-like objects</span></a> and produces <a class="reference internal" href="stdtypes#bytes" title="bytes"><code>bytes</code></a> objects. No encoding, decoding, or newline translation is performed. This category of streams can be used for all kinds of non-text data, and also when manual control over the handling of text data is desired.</p> <p>The easiest way to create a binary stream is with <a class="reference internal" href="functions#open" title="open"><code>open()</code></a> with <code>'b'</code> in the mode string:</p> <pre data-language="python">f = open("myfile.jpg", "rb")
</pre> <p>In-memory binary streams are also available as <a class="reference internal" href="#io.BytesIO" title="io.BytesIO"><code>BytesIO</code></a> objects:</p> <pre data-language="python">f = io.BytesIO(b"some initial binary data: \x00\x01")
</pre> <p>The binary stream API is described in detail in the docs of <a class="reference internal" href="#io.BufferedIOBase" title="io.BufferedIOBase"><code>BufferedIOBase</code></a>.</p> <p>Other library modules may provide additional ways to create text or binary streams. See <a class="reference internal" href="socket#socket.socket.makefile" title="socket.socket.makefile"><code>socket.socket.makefile()</code></a> for example.</p> </section> <section id="raw-i-o"> <h3>Raw I/O</h3> <p>Raw I/O (also called <em>unbuffered I/O</em>) is generally used as a low-level building-block for binary and text streams; it is rarely useful to directly manipulate a raw stream from user code. Nevertheless, you can create a raw stream by opening a file in binary mode with buffering disabled:</p> <pre data-language="python">f = open("myfile.jpg", "rb", buffering=0)
</pre> <p>The raw stream API is described in detail in the docs of <a class="reference internal" href="#io.RawIOBase" title="io.RawIOBase"><code>RawIOBase</code></a>.</p> </section> </section> <section id="text-encoding"> <span id="io-text-encoding"></span><h2>Text Encoding</h2> <p>The default encoding of <a class="reference internal" href="#io.TextIOWrapper" title="io.TextIOWrapper"><code>TextIOWrapper</code></a> and <a class="reference internal" href="functions#open" title="open"><code>open()</code></a> is locale-specific (<a class="reference internal" href="locale#locale.getencoding" title="locale.getencoding"><code>locale.getencoding()</code></a>).</p> <p>However, many developers forget to specify the encoding when opening text files encoded in UTF-8 (e.g. JSON, TOML, Markdown, etc…) since most Unix platforms use UTF-8 locale by default. This causes bugs because the locale encoding is not UTF-8 for most Windows users. For example:</p> <pre data-language="python"># May not work on Windows when non-ASCII characters in the file.
with open("README.md") as f:
    long_description = f.read()
</pre> <p>Accordingly, it is highly recommended that you specify the encoding explicitly when opening text files. If you want to use UTF-8, pass <code>encoding="utf-8"</code>. To use the current locale encoding, <code>encoding="locale"</code> is supported since Python 3.10.</p> <div class="admonition seealso"> <p class="admonition-title">See also</p> <dl class="simple"> <dt><a class="reference internal" href="os#utf8-mode"><span class="std std-ref">Python UTF-8 Mode</span></a></dt>
<dd>
<p>Python UTF-8 Mode can be used to change the default encoding to UTF-8 from locale-specific encoding.</p> </dd> <dt>
<span class="target" id="index-1"></span><a class="pep reference external" href="https://peps.python.org/pep-0686/"><strong>PEP 686</strong></a>
</dt>
<dd>
<p>Python 3.15 will make <a class="reference internal" href="os#utf8-mode"><span class="std std-ref">Python UTF-8 Mode</span></a> default.</p> </dd> </dl> </div> <section id="opt-in-encodingwarning"> <span id="io-encoding-warning"></span><h3>Opt-in EncodingWarning</h3> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.10: </span>See <span class="target" id="index-2"></span><a class="pep reference external" href="https://peps.python.org/pep-0597/"><strong>PEP 597</strong></a> for more details.</p> </div> <p>To find where the default locale encoding is used, you can enable the <a class="reference internal" href="../using/cmdline#cmdoption-X"><code>-X warn_default_encoding</code></a> command line option or set the <span class="target" id="index-3"></span><a class="reference internal" href="../using/cmdline#envvar-PYTHONWARNDEFAULTENCODING"><code>PYTHONWARNDEFAULTENCODING</code></a> environment variable, which will emit an <a class="reference internal" href="exceptions#EncodingWarning" title="EncodingWarning"><code>EncodingWarning</code></a> when the default encoding is used.</p> <p>If you are providing an API that uses <a class="reference internal" href="functions#open" title="open"><code>open()</code></a> or <a class="reference internal" href="#io.TextIOWrapper" title="io.TextIOWrapper"><code>TextIOWrapper</code></a> and passes <code>encoding=None</code> as a parameter, you can use <a class="reference internal" href="#io.text_encoding" title="io.text_encoding"><code>text_encoding()</code></a> so that callers of the API will emit an <a class="reference internal" href="exceptions#EncodingWarning" title="EncodingWarning"><code>EncodingWarning</code></a> if they don’t pass an <code>encoding</code>. However, please consider using UTF-8 by default (i.e. <code>encoding="utf-8"</code>) for new APIs.</p> </section> </section> <section id="high-level-module-interface"> <h2>High-level Module Interface</h2> <dl class="py data"> <dt class="sig sig-object py" id="io.DEFAULT_BUFFER_SIZE">
<code>io.DEFAULT_BUFFER_SIZE</code> </dt> <dd>
<p>An int containing the default buffer size used by the module’s buffered I/O classes. <a class="reference internal" href="functions#open" title="open"><code>open()</code></a> uses the file’s blksize (as obtained by <a class="reference internal" href="os#os.stat" title="os.stat"><code>os.stat()</code></a>) if possible.</p> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="io.open">
<code>io.open(file, mode='r', buffering=- 1, encoding=None, errors=None, newline=None, closefd=True, opener=None)</code> </dt> <dd>
<p>This is an alias for the builtin <a class="reference internal" href="functions#open" title="open"><code>open()</code></a> function.</p> <p class="audit-hook"></p>
<p>This function raises an <a class="reference internal" href="sys#auditing"><span class="std std-ref">auditing event</span></a> <code>open</code> with arguments <em>path</em>, <em>mode</em> and <em>flags</em>. The <em>mode</em> and <em>flags</em> arguments may have been modified or inferred from the original call.</p> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="io.open_code">
<code>io.open_code(path)</code> </dt> <dd>
<p>Opens the provided file with mode <code>'rb'</code>. This function should be used when the intent is to treat the contents as executable code.</p> <p><em>path</em> should be a <a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a> and an absolute path.</p> <p>The behavior of this function may be overridden by an earlier call to the <a class="reference internal" href="../c-api/file#c.PyFile_SetOpenCodeHook" title="PyFile_SetOpenCodeHook"><code>PyFile_SetOpenCodeHook()</code></a>. However, assuming that <em>path</em> is a <a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a> and an absolute path, <code>open_code(path)</code> should always behave the same as <code>open(path, 'rb')</code>. Overriding the behavior is intended for additional validation or preprocessing of the file.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.8.</span></p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="io.text_encoding">
<code>io.text_encoding(encoding, stacklevel=2, /)</code> </dt> <dd>
<p>This is a helper function for callables that use <a class="reference internal" href="functions#open" title="open"><code>open()</code></a> or <a class="reference internal" href="#io.TextIOWrapper" title="io.TextIOWrapper"><code>TextIOWrapper</code></a> and have an <code>encoding=None</code> parameter.</p> <p>This function returns <em>encoding</em> if it is not <code>None</code>. Otherwise, it returns <code>"locale"</code> or <code>"utf-8"</code> depending on <a class="reference internal" href="os#utf8-mode"><span class="std std-ref">UTF-8 Mode</span></a>.</p> <p>This function emits an <a class="reference internal" href="exceptions#EncodingWarning" title="EncodingWarning"><code>EncodingWarning</code></a> if <a class="reference internal" href="sys#sys.flags" title="sys.flags"><code>sys.flags.warn_default_encoding</code></a> is true and <em>encoding</em> is <code>None</code>. <em>stacklevel</em> specifies where the warning is emitted. For example:</p> <pre data-language="python">def read_text(path, encoding=None):
    encoding = io.text_encoding(encoding)  # stacklevel=2
    with open(path, encoding) as f:
        return f.read()
</pre> <p>In this example, an <a class="reference internal" href="exceptions#EncodingWarning" title="EncodingWarning"><code>EncodingWarning</code></a> is emitted for the caller of <code>read_text()</code>.</p> <p>See <a class="reference internal" href="#io-text-encoding"><span class="std std-ref">Text Encoding</span></a> for more information.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.10.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span><a class="reference internal" href="#io.text_encoding" title="io.text_encoding"><code>text_encoding()</code></a> returns “utf-8” when UTF-8 mode is enabled and <em>encoding</em> is <code>None</code>.</p> </div> </dd>
</dl> <dl class="py exception"> <dt class="sig sig-object py" id="io.BlockingIOError">
<code>exception io.BlockingIOError</code> </dt> <dd>
<p>This is a compatibility alias for the builtin <a class="reference internal" href="exceptions#BlockingIOError" title="BlockingIOError"><code>BlockingIOError</code></a> exception.</p> </dd>
</dl> <dl class="py exception"> <dt class="sig sig-object py" id="io.UnsupportedOperation">
<code>exception io.UnsupportedOperation</code> </dt> <dd>
<p>An exception inheriting <a class="reference internal" href="exceptions#OSError" title="OSError"><code>OSError</code></a> and <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a> that is raised when an unsupported operation is called on a stream.</p> </dd>
</dl> <div class="admonition seealso"> <p class="admonition-title">See also</p> <dl class="simple"> <dt>
<code></code> <a class="reference internal" href="sys#module-sys" title="sys: Access system-specific parameters and functions."><code>sys</code></a>
</dt>
<dd>
<p>contains the standard IO streams: <a class="reference internal" href="sys#sys.stdin" title="sys.stdin"><code>sys.stdin</code></a>, <a class="reference internal" href="sys#sys.stdout" title="sys.stdout"><code>sys.stdout</code></a>, and <a class="reference internal" href="sys#sys.stderr" title="sys.stderr"><code>sys.stderr</code></a>.</p> </dd> </dl> </div> </section> <section id="class-hierarchy"> <h2>Class hierarchy</h2> <p>The implementation of I/O streams is organized as a hierarchy of classes. First <a class="reference internal" href="../glossary#term-abstract-base-class"><span class="xref std std-term">abstract base classes</span></a> (ABCs), which are used to specify the various categories of streams, then concrete classes providing the standard stream implementations.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>The abstract base classes also provide default implementations of some methods in order to help implementation of concrete stream classes. For example, <a class="reference internal" href="#io.BufferedIOBase" title="io.BufferedIOBase"><code>BufferedIOBase</code></a> provides unoptimized implementations of <code>readinto()</code> and <code>readline()</code>.</p> </div> <p>At the top of the I/O hierarchy is the abstract base class <a class="reference internal" href="#io.IOBase" title="io.IOBase"><code>IOBase</code></a>. It defines the basic interface to a stream. Note, however, that there is no separation between reading and writing to streams; implementations are allowed to raise <a class="reference internal" href="#io.UnsupportedOperation" title="io.UnsupportedOperation"><code>UnsupportedOperation</code></a> if they do not support a given operation.</p> <p>The <a class="reference internal" href="#io.RawIOBase" title="io.RawIOBase"><code>RawIOBase</code></a> ABC extends <a class="reference internal" href="#io.IOBase" title="io.IOBase"><code>IOBase</code></a>. It deals with the reading and writing of bytes to a stream. <a class="reference internal" href="#io.FileIO" title="io.FileIO"><code>FileIO</code></a> subclasses <a class="reference internal" href="#io.RawIOBase" title="io.RawIOBase"><code>RawIOBase</code></a> to provide an interface to files in the machine’s file system.</p> <p>The <a class="reference internal" href="#io.BufferedIOBase" title="io.BufferedIOBase"><code>BufferedIOBase</code></a> ABC extends <a class="reference internal" href="#io.IOBase" title="io.IOBase"><code>IOBase</code></a>. It deals with buffering on a raw binary stream (<a class="reference internal" href="#io.RawIOBase" title="io.RawIOBase"><code>RawIOBase</code></a>). Its subclasses, <a class="reference internal" href="#io.BufferedWriter" title="io.BufferedWriter"><code>BufferedWriter</code></a>, <a class="reference internal" href="#io.BufferedReader" title="io.BufferedReader"><code>BufferedReader</code></a>, and <a class="reference internal" href="#io.BufferedRWPair" title="io.BufferedRWPair"><code>BufferedRWPair</code></a> buffer raw binary streams that are writable, readable, and both readable and writable, respectively. <a class="reference internal" href="#io.BufferedRandom" title="io.BufferedRandom"><code>BufferedRandom</code></a> provides a buffered interface to seekable streams. Another <a class="reference internal" href="#io.BufferedIOBase" title="io.BufferedIOBase"><code>BufferedIOBase</code></a> subclass, <a class="reference internal" href="#io.BytesIO" title="io.BytesIO"><code>BytesIO</code></a>, is a stream of in-memory bytes.</p> <p>The <a class="reference internal" href="#io.TextIOBase" title="io.TextIOBase"><code>TextIOBase</code></a> ABC extends <a class="reference internal" href="#io.IOBase" title="io.IOBase"><code>IOBase</code></a>. It deals with streams whose bytes represent text, and handles encoding and decoding to and from strings. <a class="reference internal" href="#io.TextIOWrapper" title="io.TextIOWrapper"><code>TextIOWrapper</code></a>, which extends <a class="reference internal" href="#io.TextIOBase" title="io.TextIOBase"><code>TextIOBase</code></a>, is a buffered text interface to a buffered raw stream (<a class="reference internal" href="#io.BufferedIOBase" title="io.BufferedIOBase"><code>BufferedIOBase</code></a>). Finally, <a class="reference internal" href="#io.StringIO" title="io.StringIO"><code>StringIO</code></a> is an in-memory stream for text.</p> <p>Argument names are not part of the specification, and only the arguments of <a class="reference internal" href="functions#open" title="open"><code>open()</code></a> are intended to be used as keyword arguments.</p> <p>The following table summarizes the ABCs provided by the <a class="reference internal" href="#module-io" title="io: Core tools for working with streams."><code>io</code></a> module:</p> <table class="docutils align-default">  <thead> <tr>
<th class="head"><p>ABC</p></th> <th class="head"><p>Inherits</p></th> <th class="head"><p>Stub Methods</p></th> <th class="head"><p>Mixin Methods and Properties</p></th> </tr> </thead>  <tr>
<td><p><a class="reference internal" href="#io.IOBase" title="io.IOBase"><code>IOBase</code></a></p></td> <td></td> <td><p><code>fileno</code>, <code>seek</code>, and <code>truncate</code></p></td> <td><p><code>close</code>, <code>closed</code>, <code>__enter__</code>, <code>__exit__</code>, <code>flush</code>, <code>isatty</code>, <code>__iter__</code>, <code>__next__</code>, <code>readable</code>, <code>readline</code>, <code>readlines</code>, <code>seekable</code>, <code>tell</code>, <code>writable</code>, and <code>writelines</code></p></td> </tr> <tr>
<td><p><a class="reference internal" href="#io.RawIOBase" title="io.RawIOBase"><code>RawIOBase</code></a></p></td> <td><p><a class="reference internal" href="#io.IOBase" title="io.IOBase"><code>IOBase</code></a></p></td> <td><p><code>readinto</code> and <code>write</code></p></td> <td><p>Inherited <a class="reference internal" href="#io.IOBase" title="io.IOBase"><code>IOBase</code></a> methods, <code>read</code>, and <code>readall</code></p></td> </tr> <tr>
<td><p><a class="reference internal" href="#io.BufferedIOBase" title="io.BufferedIOBase"><code>BufferedIOBase</code></a></p></td> <td><p><a class="reference internal" href="#io.IOBase" title="io.IOBase"><code>IOBase</code></a></p></td> <td><p><code>detach</code>, <code>read</code>, <code>read1</code>, and <code>write</code></p></td> <td><p>Inherited <a class="reference internal" href="#io.IOBase" title="io.IOBase"><code>IOBase</code></a> methods, <code>readinto</code>, and <code>readinto1</code></p></td> </tr> <tr>
<td><p><a class="reference internal" href="#io.TextIOBase" title="io.TextIOBase"><code>TextIOBase</code></a></p></td> <td><p><a class="reference internal" href="#io.IOBase" title="io.IOBase"><code>IOBase</code></a></p></td> <td><p><code>detach</code>, <code>read</code>, <code>readline</code>, and <code>write</code></p></td> <td><p>Inherited <a class="reference internal" href="#io.IOBase" title="io.IOBase"><code>IOBase</code></a> methods, <code>encoding</code>, <code>errors</code>, and <code>newlines</code></p></td> </tr>  </table> <section id="i-o-base-classes"> <h3>I/O Base Classes</h3> <dl class="py class"> <dt class="sig sig-object py" id="io.IOBase">
<code>class io.IOBase</code> </dt> <dd>
<p>The abstract base class for all I/O classes.</p> <p>This class provides empty abstract implementations for many methods that derived classes can override selectively; the default implementations represent a file that cannot be read, written or seeked.</p> <p>Even though <a class="reference internal" href="#io.IOBase" title="io.IOBase"><code>IOBase</code></a> does not declare <code>read()</code> or <code>write()</code> because their signatures will vary, implementations and clients should consider those methods part of the interface. Also, implementations may raise a <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a> (or <a class="reference internal" href="#io.UnsupportedOperation" title="io.UnsupportedOperation"><code>UnsupportedOperation</code></a>) when operations they do not support are called.</p> <p>The basic type used for binary data read from or written to a file is <a class="reference internal" href="stdtypes#bytes" title="bytes"><code>bytes</code></a>. Other <a class="reference internal" href="../glossary#term-bytes-like-object"><span class="xref std std-term">bytes-like objects</span></a> are accepted as method arguments too. Text I/O classes work with <a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a> data.</p> <p>Note that calling any method (even inquiries) on a closed stream is undefined. Implementations may raise <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a> in this case.</p> <p><a class="reference internal" href="#io.IOBase" title="io.IOBase"><code>IOBase</code></a> (and its subclasses) supports the iterator protocol, meaning that an <a class="reference internal" href="#io.IOBase" title="io.IOBase"><code>IOBase</code></a> object can be iterated over yielding the lines in a stream. Lines are defined slightly differently depending on whether the stream is a binary stream (yielding bytes), or a text stream (yielding character strings). See <a class="reference internal" href="#io.IOBase.readline" title="io.IOBase.readline"><code>readline()</code></a> below.</p> <p><a class="reference internal" href="#io.IOBase" title="io.IOBase"><code>IOBase</code></a> is also a context manager and therefore supports the <a class="reference internal" href="../reference/compound_stmts#with"><code>with</code></a> statement. In this example, <em>file</em> is closed after the <code>with</code> statement’s suite is finished—even if an exception occurs:</p> <pre data-language="python">with open('spam.txt', 'w') as file:
    file.write('Spam and eggs!')
</pre> <p><a class="reference internal" href="#io.IOBase" title="io.IOBase"><code>IOBase</code></a> provides these data attributes and methods:</p> <dl class="py method"> <dt class="sig sig-object py" id="io.IOBase.close">
<code>close()</code> </dt> <dd>
<p>Flush and close this stream. This method has no effect if the file is already closed. Once the file is closed, any operation on the file (e.g. reading or writing) will raise a <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a>.</p> <p>As a convenience, it is allowed to call this method more than once; only the first call, however, will have an effect.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="io.IOBase.closed">
<code>closed</code> </dt> <dd>
<p><code>True</code> if the stream is closed.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="io.IOBase.fileno">
<code>fileno()</code> </dt> <dd>
<p>Return the underlying file descriptor (an integer) of the stream if it exists. An <a class="reference internal" href="exceptions#OSError" title="OSError"><code>OSError</code></a> is raised if the IO object does not use a file descriptor.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="io.IOBase.flush">
<code>flush()</code> </dt> <dd>
<p>Flush the write buffers of the stream if applicable. This does nothing for read-only and non-blocking streams.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="io.IOBase.isatty">
<code>isatty()</code> </dt> <dd>
<p>Return <code>True</code> if the stream is interactive (i.e., connected to a terminal/tty device).</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="io.IOBase.readable">
<code>readable()</code> </dt> <dd>
<p>Return <code>True</code> if the stream can be read from. If <code>False</code>, <code>read()</code> will raise <a class="reference internal" href="exceptions#OSError" title="OSError"><code>OSError</code></a>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="io.IOBase.readline">
<code>readline(size=- 1, /)</code> </dt> <dd>
<p>Read and return one line from the stream. If <em>size</em> is specified, at most <em>size</em> bytes will be read.</p> <p>The line terminator is always <code>b'\n'</code> for binary files; for text files, the <em>newline</em> argument to <a class="reference internal" href="functions#open" title="open"><code>open()</code></a> can be used to select the line terminator(s) recognized.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="io.IOBase.readlines">
<code>readlines(hint=- 1, /)</code> </dt> <dd>
<p>Read and return a list of lines from the stream. <em>hint</em> can be specified to control the number of lines read: no more lines will be read if the total size (in bytes/characters) of all lines so far exceeds <em>hint</em>.</p> <p><em>hint</em> values of <code>0</code> or less, as well as <code>None</code>, are treated as no hint.</p> <p>Note that it’s already possible to iterate on file objects using <code>for
line in file: ...</code> without calling <code>file.readlines()</code>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="io.IOBase.seek">
<code>seek(offset, whence=os.SEEK_SET, /)</code> </dt> <dd>
<p>Change the stream position to the given byte <em>offset</em>, interpreted relative to the position indicated by <em>whence</em>, and return the new absolute position. Values for <em>whence</em> are:</p> <ul class="simple"> <li>
<a class="reference internal" href="os#os.SEEK_SET" title="os.SEEK_SET"><code>os.SEEK_SET</code></a> or <code>0</code> – start of the stream (the default); <em>offset</em> should be zero or positive</li> <li>
<a class="reference internal" href="os#os.SEEK_CUR" title="os.SEEK_CUR"><code>os.SEEK_CUR</code></a> or <code>1</code> – current stream position; <em>offset</em> may be negative</li> <li>
<a class="reference internal" href="os#os.SEEK_END" title="os.SEEK_END"><code>os.SEEK_END</code></a> or <code>2</code> – end of the stream; <em>offset</em> is usually negative</li> </ul> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.1: </span>The <code>SEEK_*</code> constants.</p> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.3: </span>Some operating systems could support additional values, like <a class="reference internal" href="os#os.SEEK_HOLE" title="os.SEEK_HOLE"><code>os.SEEK_HOLE</code></a> or <a class="reference internal" href="os#os.SEEK_DATA" title="os.SEEK_DATA"><code>os.SEEK_DATA</code></a>. The valid values for a file could depend on it being open in text or binary mode.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="io.IOBase.seekable">
<code>seekable()</code> </dt> <dd>
<p>Return <code>True</code> if the stream supports random access. If <code>False</code>, <a class="reference internal" href="#io.IOBase.seek" title="io.IOBase.seek"><code>seek()</code></a>, <a class="reference internal" href="#io.IOBase.tell" title="io.IOBase.tell"><code>tell()</code></a> and <a class="reference internal" href="#io.IOBase.truncate" title="io.IOBase.truncate"><code>truncate()</code></a> will raise <a class="reference internal" href="exceptions#OSError" title="OSError"><code>OSError</code></a>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="io.IOBase.tell">
<code>tell()</code> </dt> <dd>
<p>Return the current stream position.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="io.IOBase.truncate">
<code>truncate(size=None, /)</code> </dt> <dd>
<p>Resize the stream to the given <em>size</em> in bytes (or the current position if <em>size</em> is not specified). The current stream position isn’t changed. This resizing can extend or reduce the current file size. In case of extension, the contents of the new file area depend on the platform (on most systems, additional bytes are zero-filled). The new file size is returned.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>Windows will now zero-fill files when extending.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="io.IOBase.writable">
<code>writable()</code> </dt> <dd>
<p>Return <code>True</code> if the stream supports writing. If <code>False</code>, <code>write()</code> and <a class="reference internal" href="#io.IOBase.truncate" title="io.IOBase.truncate"><code>truncate()</code></a> will raise <a class="reference internal" href="exceptions#OSError" title="OSError"><code>OSError</code></a>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="io.IOBase.writelines">
<code>writelines(lines, /)</code> </dt> <dd>
<p>Write a list of lines to the stream. Line separators are not added, so it is usual for each of the lines provided to have a line separator at the end.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="io.IOBase.__del__">
<code>__del__()</code> </dt> <dd>
<p>Prepare for object destruction. <a class="reference internal" href="#io.IOBase" title="io.IOBase"><code>IOBase</code></a> provides a default implementation of this method that calls the instance’s <a class="reference internal" href="#io.IOBase.close" title="io.IOBase.close"><code>close()</code></a> method.</p> </dd>
</dl> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="io.RawIOBase">
<code>class io.RawIOBase</code> </dt> <dd>
<p>Base class for raw binary streams. It inherits <a class="reference internal" href="#io.IOBase" title="io.IOBase"><code>IOBase</code></a>.</p> <p>Raw binary streams typically provide low-level access to an underlying OS device or API, and do not try to encapsulate it in high-level primitives (this functionality is done at a higher-level in buffered binary streams and text streams, described later in this page).</p> <p><a class="reference internal" href="#io.RawIOBase" title="io.RawIOBase"><code>RawIOBase</code></a> provides these methods in addition to those from <a class="reference internal" href="#io.IOBase" title="io.IOBase"><code>IOBase</code></a>:</p> <dl class="py method"> <dt class="sig sig-object py" id="io.RawIOBase.read">
<code>read(size=- 1, /)</code> </dt> <dd>
<p>Read up to <em>size</em> bytes from the object and return them. As a convenience, if <em>size</em> is unspecified or -1, all bytes until EOF are returned. Otherwise, only one system call is ever made. Fewer than <em>size</em> bytes may be returned if the operating system call returns fewer than <em>size</em> bytes.</p> <p>If 0 bytes are returned, and <em>size</em> was not 0, this indicates end of file. If the object is in non-blocking mode and no bytes are available, <code>None</code> is returned.</p> <p>The default implementation defers to <a class="reference internal" href="#io.RawIOBase.readall" title="io.RawIOBase.readall"><code>readall()</code></a> and <a class="reference internal" href="#io.RawIOBase.readinto" title="io.RawIOBase.readinto"><code>readinto()</code></a>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="io.RawIOBase.readall">
<code>readall()</code> </dt> <dd>
<p>Read and return all the bytes from the stream until EOF, using multiple calls to the stream if necessary.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="io.RawIOBase.readinto">
<code>readinto(b, /)</code> </dt> <dd>
<p>Read bytes into a pre-allocated, writable <a class="reference internal" href="../glossary#term-bytes-like-object"><span class="xref std std-term">bytes-like object</span></a> <em>b</em>, and return the number of bytes read. For example, <em>b</em> might be a <a class="reference internal" href="stdtypes#bytearray" title="bytearray"><code>bytearray</code></a>. If the object is in non-blocking mode and no bytes are available, <code>None</code> is returned.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="io.RawIOBase.write">
<code>write(b, /)</code> </dt> <dd>
<p>Write the given <a class="reference internal" href="../glossary#term-bytes-like-object"><span class="xref std std-term">bytes-like object</span></a>, <em>b</em>, to the underlying raw stream, and return the number of bytes written. This can be less than the length of <em>b</em> in bytes, depending on specifics of the underlying raw stream, and especially if it is in non-blocking mode. <code>None</code> is returned if the raw stream is set not to block and no single byte could be readily written to it. The caller may release or mutate <em>b</em> after this method returns, so the implementation should only access <em>b</em> during the method call.</p> </dd>
</dl> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="io.BufferedIOBase">
<code>class io.BufferedIOBase</code> </dt> <dd>
<p>Base class for binary streams that support some kind of buffering. It inherits <a class="reference internal" href="#io.IOBase" title="io.IOBase"><code>IOBase</code></a>.</p> <p>The main difference with <a class="reference internal" href="#io.RawIOBase" title="io.RawIOBase"><code>RawIOBase</code></a> is that methods <a class="reference internal" href="#io.BufferedIOBase.read" title="io.BufferedIOBase.read"><code>read()</code></a>, <a class="reference internal" href="#io.BufferedIOBase.readinto" title="io.BufferedIOBase.readinto"><code>readinto()</code></a> and <a class="reference internal" href="#io.BufferedIOBase.write" title="io.BufferedIOBase.write"><code>write()</code></a> will try (respectively) to read as much input as requested or to consume all given output, at the expense of making perhaps more than one system call.</p> <p>In addition, those methods can raise <a class="reference internal" href="exceptions#BlockingIOError" title="BlockingIOError"><code>BlockingIOError</code></a> if the underlying raw stream is in non-blocking mode and cannot take or give enough data; unlike their <a class="reference internal" href="#io.RawIOBase" title="io.RawIOBase"><code>RawIOBase</code></a> counterparts, they will never return <code>None</code>.</p> <p>Besides, the <a class="reference internal" href="#io.BufferedIOBase.read" title="io.BufferedIOBase.read"><code>read()</code></a> method does not have a default implementation that defers to <a class="reference internal" href="#io.BufferedIOBase.readinto" title="io.BufferedIOBase.readinto"><code>readinto()</code></a>.</p> <p>A typical <a class="reference internal" href="#io.BufferedIOBase" title="io.BufferedIOBase"><code>BufferedIOBase</code></a> implementation should not inherit from a <a class="reference internal" href="#io.RawIOBase" title="io.RawIOBase"><code>RawIOBase</code></a> implementation, but wrap one, like <a class="reference internal" href="#io.BufferedWriter" title="io.BufferedWriter"><code>BufferedWriter</code></a> and <a class="reference internal" href="#io.BufferedReader" title="io.BufferedReader"><code>BufferedReader</code></a> do.</p> <p><a class="reference internal" href="#io.BufferedIOBase" title="io.BufferedIOBase"><code>BufferedIOBase</code></a> provides or overrides these data attributes and methods in addition to those from <a class="reference internal" href="#io.IOBase" title="io.IOBase"><code>IOBase</code></a>:</p> <dl class="py attribute"> <dt class="sig sig-object py" id="io.BufferedIOBase.raw">
<code>raw</code> </dt> <dd>
<p>The underlying raw stream (a <a class="reference internal" href="#io.RawIOBase" title="io.RawIOBase"><code>RawIOBase</code></a> instance) that <a class="reference internal" href="#io.BufferedIOBase" title="io.BufferedIOBase"><code>BufferedIOBase</code></a> deals with. This is not part of the <a class="reference internal" href="#io.BufferedIOBase" title="io.BufferedIOBase"><code>BufferedIOBase</code></a> API and may not exist on some implementations.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="io.BufferedIOBase.detach">
<code>detach()</code> </dt> <dd>
<p>Separate the underlying raw stream from the buffer and return it.</p> <p>After the raw stream has been detached, the buffer is in an unusable state.</p> <p>Some buffers, like <a class="reference internal" href="#io.BytesIO" title="io.BytesIO"><code>BytesIO</code></a>, do not have the concept of a single raw stream to return from this method. They raise <a class="reference internal" href="#io.UnsupportedOperation" title="io.UnsupportedOperation"><code>UnsupportedOperation</code></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.1.</span></p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="io.BufferedIOBase.read">
<code>read(size=- 1, /)</code> </dt> <dd>
<p>Read and return up to <em>size</em> bytes. If the argument is omitted, <code>None</code>, or negative, data is read and returned until EOF is reached. An empty <a class="reference internal" href="stdtypes#bytes" title="bytes"><code>bytes</code></a> object is returned if the stream is already at EOF.</p> <p>If the argument is positive, and the underlying raw stream is not interactive, multiple raw reads may be issued to satisfy the byte count (unless EOF is reached first). But for interactive raw streams, at most one raw read will be issued, and a short result does not imply that EOF is imminent.</p> <p>A <a class="reference internal" href="exceptions#BlockingIOError" title="BlockingIOError"><code>BlockingIOError</code></a> is raised if the underlying raw stream is in non blocking-mode, and has no data available at the moment.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="io.BufferedIOBase.read1">
<code>read1(size=- 1, /)</code> </dt> <dd>
<p>Read and return up to <em>size</em> bytes, with at most one call to the underlying raw stream’s <a class="reference internal" href="#io.RawIOBase.read" title="io.RawIOBase.read"><code>read()</code></a> (or <a class="reference internal" href="#io.RawIOBase.readinto" title="io.RawIOBase.readinto"><code>readinto()</code></a>) method. This can be useful if you are implementing your own buffering on top of a <a class="reference internal" href="#io.BufferedIOBase" title="io.BufferedIOBase"><code>BufferedIOBase</code></a> object.</p> <p>If <em>size</em> is <code>-1</code> (the default), an arbitrary number of bytes are returned (more than zero unless EOF is reached).</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="io.BufferedIOBase.readinto">
<code>readinto(b, /)</code> </dt> <dd>
<p>Read bytes into a pre-allocated, writable <a class="reference internal" href="../glossary#term-bytes-like-object"><span class="xref std std-term">bytes-like object</span></a> <em>b</em> and return the number of bytes read. For example, <em>b</em> might be a <a class="reference internal" href="stdtypes#bytearray" title="bytearray"><code>bytearray</code></a>.</p> <p>Like <a class="reference internal" href="#io.BufferedIOBase.read" title="io.BufferedIOBase.read"><code>read()</code></a>, multiple reads may be issued to the underlying raw stream, unless the latter is interactive.</p> <p>A <a class="reference internal" href="exceptions#BlockingIOError" title="BlockingIOError"><code>BlockingIOError</code></a> is raised if the underlying raw stream is in non blocking-mode, and has no data available at the moment.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="io.BufferedIOBase.readinto1">
<code>readinto1(b, /)</code> </dt> <dd>
<p>Read bytes into a pre-allocated, writable <a class="reference internal" href="../glossary#term-bytes-like-object"><span class="xref std std-term">bytes-like object</span></a> <em>b</em>, using at most one call to the underlying raw stream’s <a class="reference internal" href="#io.RawIOBase.read" title="io.RawIOBase.read"><code>read()</code></a> (or <a class="reference internal" href="#io.RawIOBase.readinto" title="io.RawIOBase.readinto"><code>readinto()</code></a>) method. Return the number of bytes read.</p> <p>A <a class="reference internal" href="exceptions#BlockingIOError" title="BlockingIOError"><code>BlockingIOError</code></a> is raised if the underlying raw stream is in non blocking-mode, and has no data available at the moment.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5.</span></p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="io.BufferedIOBase.write">
<code>write(b, /)</code> </dt> <dd>
<p>Write the given <a class="reference internal" href="../glossary#term-bytes-like-object"><span class="xref std std-term">bytes-like object</span></a>, <em>b</em>, and return the number of bytes written (always equal to the length of <em>b</em> in bytes, since if the write fails an <a class="reference internal" href="exceptions#OSError" title="OSError"><code>OSError</code></a> will be raised). Depending on the actual implementation, these bytes may be readily written to the underlying stream, or held in a buffer for performance and latency reasons.</p> <p>When in non-blocking mode, a <a class="reference internal" href="exceptions#BlockingIOError" title="BlockingIOError"><code>BlockingIOError</code></a> is raised if the data needed to be written to the raw stream but it couldn’t accept all the data without blocking.</p> <p>The caller may release or mutate <em>b</em> after this method returns, so the implementation should only access <em>b</em> during the method call.</p> </dd>
</dl> </dd>
</dl> </section> <section id="raw-file-i-o"> <h3>Raw File I/O</h3> <dl class="py class"> <dt class="sig sig-object py" id="io.FileIO">
<code>class io.FileIO(name, mode='r', closefd=True, opener=None)</code> </dt> <dd>
<p>A raw binary stream representing an OS-level file containing bytes data. It inherits <a class="reference internal" href="#io.RawIOBase" title="io.RawIOBase"><code>RawIOBase</code></a>.</p> <p>The <em>name</em> can be one of two things:</p> <ul class="simple"> <li>a character string or <a class="reference internal" href="stdtypes#bytes" title="bytes"><code>bytes</code></a> object representing the path to the file which will be opened. In this case closefd must be <code>True</code> (the default) otherwise an error will be raised.</li> <li>an integer representing the number of an existing OS-level file descriptor to which the resulting <a class="reference internal" href="#io.FileIO" title="io.FileIO"><code>FileIO</code></a> object will give access. When the FileIO object is closed this fd will be closed as well, unless <em>closefd</em> is set to <code>False</code>.</li> </ul> <p>The <em>mode</em> can be <code>'r'</code>, <code>'w'</code>, <code>'x'</code> or <code>'a'</code> for reading (default), writing, exclusive creation or appending. The file will be created if it doesn’t exist when opened for writing or appending; it will be truncated when opened for writing. <a class="reference internal" href="exceptions#FileExistsError" title="FileExistsError"><code>FileExistsError</code></a> will be raised if it already exists when opened for creating. Opening a file for creating implies writing, so this mode behaves in a similar way to <code>'w'</code>. Add a <code>'+'</code> to the mode to allow simultaneous reading and writing.</p> <p>The <a class="reference internal" href="#io.RawIOBase.read" title="io.RawIOBase.read"><code>read()</code></a> (when called with a positive argument), <a class="reference internal" href="#io.RawIOBase.readinto" title="io.RawIOBase.readinto"><code>readinto()</code></a> and <a class="reference internal" href="#io.RawIOBase.write" title="io.RawIOBase.write"><code>write()</code></a> methods on this class will only make one system call.</p> <p>A custom opener can be used by passing a callable as <em>opener</em>. The underlying file descriptor for the file object is then obtained by calling <em>opener</em> with (<em>name</em>, <em>flags</em>). <em>opener</em> must return an open file descriptor (passing <a class="reference internal" href="os#os.open" title="os.open"><code>os.open</code></a> as <em>opener</em> results in functionality similar to passing <code>None</code>).</p> <p>The newly created file is <a class="reference internal" href="os#fd-inheritance"><span class="std std-ref">non-inheritable</span></a>.</p> <p>See the <a class="reference internal" href="functions#open" title="open"><code>open()</code></a> built-in function for examples on using the <em>opener</em> parameter.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.3: </span>The <em>opener</em> parameter was added. The <code>'x'</code> mode was added.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.4: </span>The file is now non-inheritable.</p> </div> <p><a class="reference internal" href="#io.FileIO" title="io.FileIO"><code>FileIO</code></a> provides these data attributes in addition to those from <a class="reference internal" href="#io.RawIOBase" title="io.RawIOBase"><code>RawIOBase</code></a> and <a class="reference internal" href="#io.IOBase" title="io.IOBase"><code>IOBase</code></a>:</p> <dl class="py attribute"> <dt class="sig sig-object py" id="io.FileIO.mode">
<code>mode</code> </dt> <dd>
<p>The mode as given in the constructor.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="io.FileIO.name">
<code>name</code> </dt> <dd>
<p>The file name. This is the file descriptor of the file when no name is given in the constructor.</p> </dd>
</dl> </dd>
</dl> </section> <section id="buffered-streams"> <h3>Buffered Streams</h3> <p>Buffered I/O streams provide a higher-level interface to an I/O device than raw I/O does.</p> <dl class="py class"> <dt class="sig sig-object py" id="io.BytesIO">
<code>class io.BytesIO(initial_bytes=b'')</code> </dt> <dd>
<p>A binary stream using an in-memory bytes buffer. It inherits <a class="reference internal" href="#io.BufferedIOBase" title="io.BufferedIOBase"><code>BufferedIOBase</code></a>. The buffer is discarded when the <a class="reference internal" href="#io.IOBase.close" title="io.IOBase.close"><code>close()</code></a> method is called.</p> <p>The optional argument <em>initial_bytes</em> is a <a class="reference internal" href="../glossary#term-bytes-like-object"><span class="xref std std-term">bytes-like object</span></a> that contains initial data.</p> <p><a class="reference internal" href="#io.BytesIO" title="io.BytesIO"><code>BytesIO</code></a> provides or overrides these methods in addition to those from <a class="reference internal" href="#io.BufferedIOBase" title="io.BufferedIOBase"><code>BufferedIOBase</code></a> and <a class="reference internal" href="#io.IOBase" title="io.IOBase"><code>IOBase</code></a>:</p> <dl class="py method"> <dt class="sig sig-object py" id="io.BytesIO.getbuffer">
<code>getbuffer()</code> </dt> <dd>
<p>Return a readable and writable view over the contents of the buffer without copying them. Also, mutating the view will transparently update the contents of the buffer:</p> <pre data-language="python">&gt;&gt;&gt; b = io.BytesIO(b"abcdef")
&gt;&gt;&gt; view = b.getbuffer()
&gt;&gt;&gt; view[2:4] = b"56"
&gt;&gt;&gt; b.getvalue()
b'ab56ef'
</pre> <div class="admonition note"> <p class="admonition-title">Note</p> <p>As long as the view exists, the <a class="reference internal" href="#io.BytesIO" title="io.BytesIO"><code>BytesIO</code></a> object cannot be resized or closed.</p> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="io.BytesIO.getvalue">
<code>getvalue()</code> </dt> <dd>
<p>Return <a class="reference internal" href="stdtypes#bytes" title="bytes"><code>bytes</code></a> containing the entire contents of the buffer.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="io.BytesIO.read1">
<code>read1(size=- 1, /)</code> </dt> <dd>
<p>In <a class="reference internal" href="#io.BytesIO" title="io.BytesIO"><code>BytesIO</code></a>, this is the same as <a class="reference internal" href="#io.BufferedIOBase.read" title="io.BufferedIOBase.read"><code>read()</code></a>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>The <em>size</em> argument is now optional.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="io.BytesIO.readinto1">
<code>readinto1(b, /)</code> </dt> <dd>
<p>In <a class="reference internal" href="#io.BytesIO" title="io.BytesIO"><code>BytesIO</code></a>, this is the same as <a class="reference internal" href="#io.BufferedIOBase.readinto" title="io.BufferedIOBase.readinto"><code>readinto()</code></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5.</span></p> </div> </dd>
</dl> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="io.BufferedReader">
<code>class io.BufferedReader(raw, buffer_size=DEFAULT_BUFFER_SIZE)</code> </dt> <dd>
<p>A buffered binary stream providing higher-level access to a readable, non seekable <a class="reference internal" href="#io.RawIOBase" title="io.RawIOBase"><code>RawIOBase</code></a> raw binary stream. It inherits <a class="reference internal" href="#io.BufferedIOBase" title="io.BufferedIOBase"><code>BufferedIOBase</code></a>.</p> <p>When reading data from this object, a larger amount of data may be requested from the underlying raw stream, and kept in an internal buffer. The buffered data can then be returned directly on subsequent reads.</p> <p>The constructor creates a <a class="reference internal" href="#io.BufferedReader" title="io.BufferedReader"><code>BufferedReader</code></a> for the given readable <em>raw</em> stream and <em>buffer_size</em>. If <em>buffer_size</em> is omitted, <a class="reference internal" href="#io.DEFAULT_BUFFER_SIZE" title="io.DEFAULT_BUFFER_SIZE"><code>DEFAULT_BUFFER_SIZE</code></a> is used.</p> <p><a class="reference internal" href="#io.BufferedReader" title="io.BufferedReader"><code>BufferedReader</code></a> provides or overrides these methods in addition to those from <a class="reference internal" href="#io.BufferedIOBase" title="io.BufferedIOBase"><code>BufferedIOBase</code></a> and <a class="reference internal" href="#io.IOBase" title="io.IOBase"><code>IOBase</code></a>:</p> <dl class="py method"> <dt class="sig sig-object py" id="io.BufferedReader.peek">
<code>peek(size=0, /)</code> </dt> <dd>
<p>Return bytes from the stream without advancing the position. At most one single read on the raw stream is done to satisfy the call. The number of bytes returned may be less or more than requested.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="io.BufferedReader.read">
<code>read(size=- 1, /)</code> </dt> <dd>
<p>Read and return <em>size</em> bytes, or if <em>size</em> is not given or negative, until EOF or if the read call would block in non-blocking mode.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="io.BufferedReader.read1">
<code>read1(size=- 1, /)</code> </dt> <dd>
<p>Read and return up to <em>size</em> bytes with only one call on the raw stream. If at least one byte is buffered, only buffered bytes are returned. Otherwise, one raw stream read call is made.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>The <em>size</em> argument is now optional.</p> </div> </dd>
</dl> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="io.BufferedWriter">
<code>class io.BufferedWriter(raw, buffer_size=DEFAULT_BUFFER_SIZE)</code> </dt> <dd>
<p>A buffered binary stream providing higher-level access to a writeable, non seekable <a class="reference internal" href="#io.RawIOBase" title="io.RawIOBase"><code>RawIOBase</code></a> raw binary stream. It inherits <a class="reference internal" href="#io.BufferedIOBase" title="io.BufferedIOBase"><code>BufferedIOBase</code></a>.</p> <p>When writing to this object, data is normally placed into an internal buffer. The buffer will be written out to the underlying <a class="reference internal" href="#io.RawIOBase" title="io.RawIOBase"><code>RawIOBase</code></a> object under various conditions, including:</p> <ul class="simple"> <li>when the buffer gets too small for all pending data;</li> <li>when <a class="reference internal" href="#io.BufferedWriter.flush" title="io.BufferedWriter.flush"><code>flush()</code></a> is called;</li> <li>when a <a class="reference internal" href="#io.IOBase.seek" title="io.IOBase.seek"><code>seek()</code></a> is requested (for <a class="reference internal" href="#io.BufferedRandom" title="io.BufferedRandom"><code>BufferedRandom</code></a> objects);</li> <li>when the <a class="reference internal" href="#io.BufferedWriter" title="io.BufferedWriter"><code>BufferedWriter</code></a> object is closed or destroyed.</li> </ul> <p>The constructor creates a <a class="reference internal" href="#io.BufferedWriter" title="io.BufferedWriter"><code>BufferedWriter</code></a> for the given writeable <em>raw</em> stream. If the <em>buffer_size</em> is not given, it defaults to <a class="reference internal" href="#io.DEFAULT_BUFFER_SIZE" title="io.DEFAULT_BUFFER_SIZE"><code>DEFAULT_BUFFER_SIZE</code></a>.</p> <p><a class="reference internal" href="#io.BufferedWriter" title="io.BufferedWriter"><code>BufferedWriter</code></a> provides or overrides these methods in addition to those from <a class="reference internal" href="#io.BufferedIOBase" title="io.BufferedIOBase"><code>BufferedIOBase</code></a> and <a class="reference internal" href="#io.IOBase" title="io.IOBase"><code>IOBase</code></a>:</p> <dl class="py method"> <dt class="sig sig-object py" id="io.BufferedWriter.flush">
<code>flush()</code> </dt> <dd>
<p>Force bytes held in the buffer into the raw stream. A <a class="reference internal" href="exceptions#BlockingIOError" title="BlockingIOError"><code>BlockingIOError</code></a> should be raised if the raw stream blocks.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="io.BufferedWriter.write">
<code>write(b, /)</code> </dt> <dd>
<p>Write the <a class="reference internal" href="../glossary#term-bytes-like-object"><span class="xref std std-term">bytes-like object</span></a>, <em>b</em>, and return the number of bytes written. When in non-blocking mode, a <a class="reference internal" href="exceptions#BlockingIOError" title="BlockingIOError"><code>BlockingIOError</code></a> is raised if the buffer needs to be written out but the raw stream blocks.</p> </dd>
</dl> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="io.BufferedRandom">
<code>class io.BufferedRandom(raw, buffer_size=DEFAULT_BUFFER_SIZE)</code> </dt> <dd>
<p>A buffered binary stream providing higher-level access to a seekable <a class="reference internal" href="#io.RawIOBase" title="io.RawIOBase"><code>RawIOBase</code></a> raw binary stream. It inherits <a class="reference internal" href="#io.BufferedReader" title="io.BufferedReader"><code>BufferedReader</code></a> and <a class="reference internal" href="#io.BufferedWriter" title="io.BufferedWriter"><code>BufferedWriter</code></a>.</p> <p>The constructor creates a reader and writer for a seekable raw stream, given in the first argument. If the <em>buffer_size</em> is omitted it defaults to <a class="reference internal" href="#io.DEFAULT_BUFFER_SIZE" title="io.DEFAULT_BUFFER_SIZE"><code>DEFAULT_BUFFER_SIZE</code></a>.</p> <p><a class="reference internal" href="#io.BufferedRandom" title="io.BufferedRandom"><code>BufferedRandom</code></a> is capable of anything <a class="reference internal" href="#io.BufferedReader" title="io.BufferedReader"><code>BufferedReader</code></a> or <a class="reference internal" href="#io.BufferedWriter" title="io.BufferedWriter"><code>BufferedWriter</code></a> can do. In addition, <a class="reference internal" href="#io.IOBase.seek" title="io.IOBase.seek"><code>seek()</code></a> and <a class="reference internal" href="#io.IOBase.tell" title="io.IOBase.tell"><code>tell()</code></a> are guaranteed to be implemented.</p> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="io.BufferedRWPair">
<code>class io.BufferedRWPair(reader, writer, buffer_size=DEFAULT_BUFFER_SIZE, /)</code> </dt> <dd>
<p>A buffered binary stream providing higher-level access to two non seekable <a class="reference internal" href="#io.RawIOBase" title="io.RawIOBase"><code>RawIOBase</code></a> raw binary streams—one readable, the other writeable. It inherits <a class="reference internal" href="#io.BufferedIOBase" title="io.BufferedIOBase"><code>BufferedIOBase</code></a>.</p> <p><em>reader</em> and <em>writer</em> are <a class="reference internal" href="#io.RawIOBase" title="io.RawIOBase"><code>RawIOBase</code></a> objects that are readable and writeable respectively. If the <em>buffer_size</em> is omitted it defaults to <a class="reference internal" href="#io.DEFAULT_BUFFER_SIZE" title="io.DEFAULT_BUFFER_SIZE"><code>DEFAULT_BUFFER_SIZE</code></a>.</p> <p><a class="reference internal" href="#io.BufferedRWPair" title="io.BufferedRWPair"><code>BufferedRWPair</code></a> implements all of <a class="reference internal" href="#io.BufferedIOBase" title="io.BufferedIOBase"><code>BufferedIOBase</code></a>'s methods except for <a class="reference internal" href="#io.BufferedIOBase.detach" title="io.BufferedIOBase.detach"><code>detach()</code></a>, which raises <a class="reference internal" href="#io.UnsupportedOperation" title="io.UnsupportedOperation"><code>UnsupportedOperation</code></a>.</p> <div class="admonition warning"> <p class="admonition-title">Warning</p> <p><a class="reference internal" href="#io.BufferedRWPair" title="io.BufferedRWPair"><code>BufferedRWPair</code></a> does not attempt to synchronize accesses to its underlying raw streams. You should not pass it the same object as reader and writer; use <a class="reference internal" href="#io.BufferedRandom" title="io.BufferedRandom"><code>BufferedRandom</code></a> instead.</p> </div> </dd>
</dl> </section> <section id="id1"> <h3>Text I/O</h3> <dl class="py class"> <dt class="sig sig-object py" id="io.TextIOBase">
<code>class io.TextIOBase</code> </dt> <dd>
<p>Base class for text streams. This class provides a character and line based interface to stream I/O. It inherits <a class="reference internal" href="#io.IOBase" title="io.IOBase"><code>IOBase</code></a>.</p> <p><a class="reference internal" href="#io.TextIOBase" title="io.TextIOBase"><code>TextIOBase</code></a> provides or overrides these data attributes and methods in addition to those from <a class="reference internal" href="#io.IOBase" title="io.IOBase"><code>IOBase</code></a>:</p> <dl class="py attribute"> <dt class="sig sig-object py" id="io.TextIOBase.encoding">
<code>encoding</code> </dt> <dd>
<p>The name of the encoding used to decode the stream’s bytes into strings, and to encode strings into bytes.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="io.TextIOBase.errors">
<code>errors</code> </dt> <dd>
<p>The error setting of the decoder or encoder.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="io.TextIOBase.newlines">
<code>newlines</code> </dt> <dd>
<p>A string, a tuple of strings, or <code>None</code>, indicating the newlines translated so far. Depending on the implementation and the initial constructor flags, this may not be available.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="io.TextIOBase.buffer">
<code>buffer</code> </dt> <dd>
<p>The underlying binary buffer (a <a class="reference internal" href="#io.BufferedIOBase" title="io.BufferedIOBase"><code>BufferedIOBase</code></a> instance) that <a class="reference internal" href="#io.TextIOBase" title="io.TextIOBase"><code>TextIOBase</code></a> deals with. This is not part of the <a class="reference internal" href="#io.TextIOBase" title="io.TextIOBase"><code>TextIOBase</code></a> API and may not exist in some implementations.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="io.TextIOBase.detach">
<code>detach()</code> </dt> <dd>
<p>Separate the underlying binary buffer from the <a class="reference internal" href="#io.TextIOBase" title="io.TextIOBase"><code>TextIOBase</code></a> and return it.</p> <p>After the underlying buffer has been detached, the <a class="reference internal" href="#io.TextIOBase" title="io.TextIOBase"><code>TextIOBase</code></a> is in an unusable state.</p> <p>Some <a class="reference internal" href="#io.TextIOBase" title="io.TextIOBase"><code>TextIOBase</code></a> implementations, like <a class="reference internal" href="#io.StringIO" title="io.StringIO"><code>StringIO</code></a>, may not have the concept of an underlying buffer and calling this method will raise <a class="reference internal" href="#io.UnsupportedOperation" title="io.UnsupportedOperation"><code>UnsupportedOperation</code></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.1.</span></p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="io.TextIOBase.read">
<code>read(size=- 1, /)</code> </dt> <dd>
<p>Read and return at most <em>size</em> characters from the stream as a single <a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a>. If <em>size</em> is negative or <code>None</code>, reads until EOF.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="io.TextIOBase.readline">
<code>readline(size=- 1, /)</code> </dt> <dd>
<p>Read until newline or EOF and return a single <a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a>. If the stream is already at EOF, an empty string is returned.</p> <p>If <em>size</em> is specified, at most <em>size</em> characters will be read.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="io.TextIOBase.seek">
<code>seek(offset, whence=SEEK_SET, /)</code> </dt> <dd>
<p>Change the stream position to the given <em>offset</em>. Behaviour depends on the <em>whence</em> parameter. The default value for <em>whence</em> is <code>SEEK_SET</code>.</p> <ul class="simple"> <li>
<code>SEEK_SET</code> or <code>0</code>: seek from the start of the stream (the default); <em>offset</em> must either be a number returned by <a class="reference internal" href="#io.TextIOBase.tell" title="io.TextIOBase.tell"><code>TextIOBase.tell()</code></a>, or zero. Any other <em>offset</em> value produces undefined behaviour.</li> <li>
<code>SEEK_CUR</code> or <code>1</code>: “seek” to the current position; <em>offset</em> must be zero, which is a no-operation (all other values are unsupported).</li> <li>
<code>SEEK_END</code> or <code>2</code>: seek to the end of the stream; <em>offset</em> must be zero (all other values are unsupported).</li> </ul> <p>Return the new absolute position as an opaque number.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.1: </span>The <code>SEEK_*</code> constants.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="io.TextIOBase.tell">
<code>tell()</code> </dt> <dd>
<p>Return the current stream position as an opaque number. The number does not usually represent a number of bytes in the underlying binary storage.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="io.TextIOBase.write">
<code>write(s, /)</code> </dt> <dd>
<p>Write the string <em>s</em> to the stream and return the number of characters written.</p> </dd>
</dl> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="io.TextIOWrapper">
<code>class io.TextIOWrapper(buffer, encoding=None, errors=None, newline=None, line_buffering=False, write_through=False)</code> </dt> <dd>
<p>A buffered text stream providing higher-level access to a <a class="reference internal" href="#io.BufferedIOBase" title="io.BufferedIOBase"><code>BufferedIOBase</code></a> buffered binary stream. It inherits <a class="reference internal" href="#io.TextIOBase" title="io.TextIOBase"><code>TextIOBase</code></a>.</p> <p><em>encoding</em> gives the name of the encoding that the stream will be decoded or encoded with. It defaults to <a class="reference internal" href="locale#locale.getencoding" title="locale.getencoding"><code>locale.getencoding()</code></a>. <code>encoding="locale"</code> can be used to specify the current locale’s encoding explicitly. See <a class="reference internal" href="#io-text-encoding"><span class="std std-ref">Text Encoding</span></a> for more information.</p> <p><em>errors</em> is an optional string that specifies how encoding and decoding errors are to be handled. Pass <code>'strict'</code> to raise a <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a> exception if there is an encoding error (the default of <code>None</code> has the same effect), or pass <code>'ignore'</code> to ignore errors. (Note that ignoring encoding errors can lead to data loss.) <code>'replace'</code> causes a replacement marker (such as <code>'?'</code>) to be inserted where there is malformed data. <code>'backslashreplace'</code> causes malformed data to be replaced by a backslashed escape sequence. When writing, <code>'xmlcharrefreplace'</code> (replace with the appropriate XML character reference) or <code>'namereplace'</code> (replace with <code>\N{...}</code> escape sequences) can be used. Any other error handling name that has been registered with <a class="reference internal" href="codecs#codecs.register_error" title="codecs.register_error"><code>codecs.register_error()</code></a> is also valid.</p> <p id="index-4"><em>newline</em> controls how line endings are handled. It can be <code>None</code>, <code>''</code>, <code>'\n'</code>, <code>'\r'</code>, and <code>'\r\n'</code>. It works as follows:</p> <ul class="simple"> <li>When reading input from the stream, if <em>newline</em> is <code>None</code>, <a class="reference internal" href="../glossary#term-universal-newlines"><span class="xref std std-term">universal newlines</span></a> mode is enabled. Lines in the input can end in <code>'\n'</code>, <code>'\r'</code>, or <code>'\r\n'</code>, and these are translated into <code>'\n'</code> before being returned to the caller. If <em>newline</em> is <code>''</code>, universal newlines mode is enabled, but line endings are returned to the caller untranslated. If <em>newline</em> has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated.</li> <li>When writing output to the stream, if <em>newline</em> is <code>None</code>, any <code>'\n'</code> characters written are translated to the system default line separator, <a class="reference internal" href="os#os.linesep" title="os.linesep"><code>os.linesep</code></a>. If <em>newline</em> is <code>''</code> or <code>'\n'</code>, no translation takes place. If <em>newline</em> is any of the other legal values, any <code>'\n'</code> characters written are translated to the given string.</li> </ul> <p>If <em>line_buffering</em> is <code>True</code>, <a class="reference internal" href="#io.IOBase.flush" title="io.IOBase.flush"><code>flush()</code></a> is implied when a call to write contains a newline character or a carriage return.</p> <p>If <em>write_through</em> is <code>True</code>, calls to <a class="reference internal" href="#io.BufferedIOBase.write" title="io.BufferedIOBase.write"><code>write()</code></a> are guaranteed not to be buffered: any data written on the <a class="reference internal" href="#io.TextIOWrapper" title="io.TextIOWrapper"><code>TextIOWrapper</code></a> object is immediately handled to its underlying binary <em>buffer</em>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.3: </span>The <em>write_through</em> argument has been added.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.3: </span>The default <em>encoding</em> is now <code>locale.getpreferredencoding(False)</code> instead of <code>locale.getpreferredencoding()</code>. Don’t change temporary the locale encoding using <a class="reference internal" href="locale#locale.setlocale" title="locale.setlocale"><code>locale.setlocale()</code></a>, use the current locale encoding instead of the user preferred encoding.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.10: </span>The <em>encoding</em> argument now supports the <code>"locale"</code> dummy encoding name.</p> </div> <p><a class="reference internal" href="#io.TextIOWrapper" title="io.TextIOWrapper"><code>TextIOWrapper</code></a> provides these data attributes and methods in addition to those from <a class="reference internal" href="#io.TextIOBase" title="io.TextIOBase"><code>TextIOBase</code></a> and <a class="reference internal" href="#io.IOBase" title="io.IOBase"><code>IOBase</code></a>:</p> <dl class="py attribute"> <dt class="sig sig-object py" id="io.TextIOWrapper.line_buffering">
<code>line_buffering</code> </dt> <dd>
<p>Whether line buffering is enabled.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="io.TextIOWrapper.write_through">
<code>write_through</code> </dt> <dd>
<p>Whether writes are passed immediately to the underlying binary buffer.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.</span></p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="io.TextIOWrapper.reconfigure">
<code>reconfigure(*, encoding=None, errors=None, newline=None, line_buffering=None, write_through=None)</code> </dt> <dd>
<p>Reconfigure this text stream using new settings for <em>encoding</em>, <em>errors</em>, <em>newline</em>, <em>line_buffering</em> and <em>write_through</em>.</p> <p>Parameters not specified keep current settings, except <code>errors='strict'</code> is used when <em>encoding</em> is specified but <em>errors</em> is not specified.</p> <p>It is not possible to change the encoding or newline if some data has already been read from the stream. On the other hand, changing encoding after write is possible.</p> <p>This method does an implicit stream flush before setting the new parameters.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span>The method supports <code>encoding="locale"</code> option.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="io.TextIOWrapper.seek">
<code>seek(cookie, whence=os.SEEK_SET, /)</code> </dt> <dd>
<p>Set the stream position. Return the new stream position as an <a class="reference internal" href="functions#int" title="int"><code>int</code></a>.</p> <p>Four operations are supported, given by the following argument combinations:</p> <ul class="simple"> <li>
<code>seek(0, SEEK_SET)</code>: Rewind to the start of the stream.</li> <li>
<code>seek(cookie, SEEK_SET)</code>: Restore a previous position; <em>cookie</em> <strong>must be</strong> a number returned by <a class="reference internal" href="#io.TextIOWrapper.tell" title="io.TextIOWrapper.tell"><code>tell()</code></a>.</li> <li>
<code>seek(0, SEEK_END)</code>: Fast-forward to the end of the stream.</li> <li>
<code>seek(0, SEEK_CUR)</code>: Leave the current stream position unchanged.</li> </ul> <p>Any other argument combinations are invalid, and may raise exceptions.</p> <div class="admonition seealso"> <p class="admonition-title">See also</p> <p><a class="reference internal" href="os#os.SEEK_SET" title="os.SEEK_SET"><code>os.SEEK_SET</code></a>, <a class="reference internal" href="os#os.SEEK_CUR" title="os.SEEK_CUR"><code>os.SEEK_CUR</code></a>, and <a class="reference internal" href="os#os.SEEK_END" title="os.SEEK_END"><code>os.SEEK_END</code></a>.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="io.TextIOWrapper.tell">
<code>tell()</code> </dt> <dd>
<p>Return the stream position as an opaque number. The return value of <code>tell()</code> can be given as input to <a class="reference internal" href="#io.TextIOWrapper.seek" title="io.TextIOWrapper.seek"><code>seek()</code></a>, to restore a previous stream position.</p> </dd>
</dl> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="io.StringIO">
<code>class io.StringIO(initial_value='', newline='\n')</code> </dt> <dd>
<p>A text stream using an in-memory text buffer. It inherits <a class="reference internal" href="#io.TextIOBase" title="io.TextIOBase"><code>TextIOBase</code></a>.</p> <p>The text buffer is discarded when the <a class="reference internal" href="#io.IOBase.close" title="io.IOBase.close"><code>close()</code></a> method is called.</p> <p>The initial value of the buffer can be set by providing <em>initial_value</em>. If newline translation is enabled, newlines will be encoded as if by <a class="reference internal" href="#io.TextIOBase.write" title="io.TextIOBase.write"><code>write()</code></a>. The stream is positioned at the start of the buffer which emulates opening an existing file in a <code>w+</code> mode, making it ready for an immediate write from the beginning or for a write that would overwrite the initial value. To emulate opening a file in an <code>a+</code> mode ready for appending, use <code>f.seek(0, io.SEEK_END)</code> to reposition the stream at the end of the buffer.</p> <p>The <em>newline</em> argument works like that of <a class="reference internal" href="#io.TextIOWrapper" title="io.TextIOWrapper"><code>TextIOWrapper</code></a>, except that when writing output to the stream, if <em>newline</em> is <code>None</code>, newlines are written as <code>\n</code> on all platforms.</p> <p><a class="reference internal" href="#io.StringIO" title="io.StringIO"><code>StringIO</code></a> provides this method in addition to those from <a class="reference internal" href="#io.TextIOBase" title="io.TextIOBase"><code>TextIOBase</code></a> and <a class="reference internal" href="#io.IOBase" title="io.IOBase"><code>IOBase</code></a>:</p> <dl class="py method"> <dt class="sig sig-object py" id="io.StringIO.getvalue">
<code>getvalue()</code> </dt> <dd>
<p>Return a <a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a> containing the entire contents of the buffer. Newlines are decoded as if by <a class="reference internal" href="#io.TextIOBase.read" title="io.TextIOBase.read"><code>read()</code></a>, although the stream position is not changed.</p> </dd>
</dl> <p>Example usage:</p> <pre data-language="python">import io

output = io.StringIO()
output.write('First line.\n')
print('Second line.', file=output)

# Retrieve file contents -- this will be
# 'First line.\nSecond line.\n'
contents = output.getvalue()

# Close object and discard memory buffer --
# .getvalue() will now raise an exception.
output.close()
</pre> </dd>
</dl> <span class="target" id="index-5"></span><dl class="py class"> <dt class="sig sig-object py" id="io.IncrementalNewlineDecoder">
<code>class io.IncrementalNewlineDecoder</code> </dt> <dd>
<p>A helper codec that decodes newlines for <a class="reference internal" href="../glossary#term-universal-newlines"><span class="xref std std-term">universal newlines</span></a> mode. It inherits <a class="reference internal" href="codecs#codecs.IncrementalDecoder" title="codecs.IncrementalDecoder"><code>codecs.IncrementalDecoder</code></a>.</p> </dd>
</dl> </section> </section> <section id="performance"> <h2>Performance</h2> <p>This section discusses the performance of the provided concrete I/O implementations.</p> <section id="id2"> <h3>Binary I/O</h3> <p>By reading and writing only large chunks of data even when the user asks for a single byte, buffered I/O hides any inefficiency in calling and executing the operating system’s unbuffered I/O routines. The gain depends on the OS and the kind of I/O which is performed. For example, on some modern OSes such as Linux, unbuffered disk I/O can be as fast as buffered I/O. The bottom line, however, is that buffered I/O offers predictable performance regardless of the platform and the backing device. Therefore, it is almost always preferable to use buffered I/O rather than unbuffered I/O for binary data.</p> </section> <section id="id3"> <h3>Text I/O</h3> <p>Text I/O over a binary storage (such as a file) is significantly slower than binary I/O over the same storage, because it requires conversions between unicode and binary data using a character codec. This can become noticeable handling huge amounts of text data like large log files. Also, <a class="reference internal" href="#io.TextIOBase.tell" title="io.TextIOBase.tell"><code>tell()</code></a> and <a class="reference internal" href="#io.TextIOBase.seek" title="io.TextIOBase.seek"><code>seek()</code></a> are both quite slow due to the reconstruction algorithm used.</p> <p><a class="reference internal" href="#io.StringIO" title="io.StringIO"><code>StringIO</code></a>, however, is a native in-memory unicode container and will exhibit similar speed to <a class="reference internal" href="#io.BytesIO" title="io.BytesIO"><code>BytesIO</code></a>.</p> </section> <section id="multi-threading"> <h3>Multi-threading</h3> <p><a class="reference internal" href="#io.FileIO" title="io.FileIO"><code>FileIO</code></a> objects are thread-safe to the extent that the operating system calls (such as <em class="manpage"><a class="manpage reference external" href="https://manpages.debian.org/read(2)">read(2)</a></em> under Unix) they wrap are thread-safe too.</p> <p>Binary buffered objects (instances of <a class="reference internal" href="#io.BufferedReader" title="io.BufferedReader"><code>BufferedReader</code></a>, <a class="reference internal" href="#io.BufferedWriter" title="io.BufferedWriter"><code>BufferedWriter</code></a>, <a class="reference internal" href="#io.BufferedRandom" title="io.BufferedRandom"><code>BufferedRandom</code></a> and <a class="reference internal" href="#io.BufferedRWPair" title="io.BufferedRWPair"><code>BufferedRWPair</code></a>) protect their internal structures using a lock; it is therefore safe to call them from multiple threads at once.</p> <p><a class="reference internal" href="#io.TextIOWrapper" title="io.TextIOWrapper"><code>TextIOWrapper</code></a> objects are not thread-safe.</p> </section> <section id="reentrancy"> <h3>Reentrancy</h3> <p>Binary buffered objects (instances of <a class="reference internal" href="#io.BufferedReader" title="io.BufferedReader"><code>BufferedReader</code></a>, <a class="reference internal" href="#io.BufferedWriter" title="io.BufferedWriter"><code>BufferedWriter</code></a>, <a class="reference internal" href="#io.BufferedRandom" title="io.BufferedRandom"><code>BufferedRandom</code></a> and <a class="reference internal" href="#io.BufferedRWPair" title="io.BufferedRWPair"><code>BufferedRWPair</code></a>) are not reentrant. While reentrant calls will not happen in normal situations, they can arise from doing I/O in a <a class="reference internal" href="signal#module-signal" title="signal: Set handlers for asynchronous events."><code>signal</code></a> handler. If a thread tries to re-enter a buffered object which it is already accessing, a <a class="reference internal" href="exceptions#RuntimeError" title="RuntimeError"><code>RuntimeError</code></a> is raised. Note this doesn’t prohibit a different thread from entering the buffered object.</p> <p>The above implicitly extends to text files, since the <a class="reference internal" href="functions#open" title="open"><code>open()</code></a> function will wrap a buffered object inside a <a class="reference internal" href="#io.TextIOWrapper" title="io.TextIOWrapper"><code>TextIOWrapper</code></a>. This includes standard streams and therefore affects the built-in <a class="reference internal" href="functions#print" title="print"><code>print()</code></a> function as well.</p> </section> </section> <div class="_attribution">
  <p class="_attribution-p">
    &copy; 2001&ndash;2023 Python Software Foundation<br>Licensed under the PSF License.<br>
    <a href="https://docs.python.org/3.12/library/io.html" class="_attribution-link">https://docs.python.org/3.12/library/io.html</a>
  </p>
</div>