mirror of
https://github.com/kennethreitz/dive-into-python3.git
synced 2026-06-05 23:10:17 +00:00
mention io.BytesIO
This commit is contained in:
+5
-1
@@ -390,7 +390,7 @@ AttributeError: '_io.BufferedReader' object has no attribute 'encoding'</samp></
|
||||
<samp class=p>>>> </samp><kbd class=pp>a_file.read()</kbd>
|
||||
<samp class=pp>'new black.'</samp></pre>
|
||||
<ol>
|
||||
<li>The <code>io</code> module contains the definition of the <code>StringIO</code> class that you can use to treat a string in memory as a file.
|
||||
<li>The <code>io</code> module defines the <code>StringIO</code> class that you can use to treat a string in memory as a file.
|
||||
<li>To create a stream object out of a string, create an instance of the <code>io.StringIO()</code> class and pass it the string you want to use as your “file” data. Now you have a stream object, and you can do all sorts of stream-like things with it.
|
||||
<li>Calling the <code>read()</code> method “reads” the entire “file,” which in the case of a <code>StringIO</code> object simply returns the original string.
|
||||
<li>Just like a real file, calling the <code>read()</code> method again returns an empty string.
|
||||
@@ -398,6 +398,10 @@ AttributeError: '_io.BufferedReader' object has no attribute 'encoding'</samp></
|
||||
<li>You can also read the string in chunks, by passing a <var>size</var> parameter to the <code>read()</code> method.
|
||||
</ol>
|
||||
|
||||
<blockquote class=note>
|
||||
<p><span class=u>☞</span><code>io.StringIO</code> lets you treat a string as a file. There’s also a <code>io.BytesIO</code> class, which lets you treat a byte array as a file.
|
||||
</blockquote>
|
||||
|
||||
<h3 id=gzip>Handling Compressed Files</h3>
|
||||
|
||||
<p>The Python standard library contains modules that support reading and writing compressed files. There are a number of different compression schemes; the two most popular on non-Windows systems are <a href=http://docs.python.org/3.1/library/gzip.html>gzip</a> and <a href=http://docs.python.org/3.1/library/bz2.html>bzip2</a>. (You may have also encountered <a href=http://docs.python.org/3.1/library/zipfile.html>PKZIP archives</a> and <a href=http://docs.python.org/3.1/library/tarfile.html>GNU Tar archives</a>. Python has modules for those, too.)
|
||||
|
||||
Reference in New Issue
Block a user