<blockquote>
<p>I want to create a stream from a string in Python so that it's equivalent to reading the string as if it's read from a text file.</p>
<h1>Is this the correct/best way to do it?</h1>
</blockquote>
<p>是的,除非你真的想把它列入名单。</p>
<p>如果它打算一行一行地被消费,那么你这样做是有意义的。</p>
<p><code>StringIO()</code>创建类似文件的对象。</p>
<p>文件对象有一个方法<code>.readlines()</code>,它将对象具体化为一个列表。不必具体化列表中的数据,您可以对其进行迭代,这是更轻松的内存:</p>
<pre><code># from StringIO import StringIO # Python 2 import
from io import StringIO # Python 3 import
txt = "foo\nbar\nbaz"
</code></pre>
<p>在这里,我们将每一行<em>追加到</em>列表中,这样我们就可以演示如何遍历类似文件的对象并对数据保持一个句柄。(更有效的方法是<code>list(file_like_io)</code>。</p>
<pre><code>m_1 = []
file_like_io = StringIO(txt)
for line in file_like_io:
m_1.append(line)
</code></pre>
<p>现在:</p>
<pre><code>>>> m_1
['foo\n', 'bar\n', 'baz']
</code></pre>
<p>您可以使用<code>seek</code>将io返回到任何索引点:</p>
<pre><code>>>> file_like_io.seek(0)
>>> file_like_io.tell() #print where we are in the object now
0
</code></pre>
<h2>如果你真的想在名单上</h2>
<p><code>.readlines()</code>将<code>StringIO</code>迭代器具体化,就像一个迭代器那样<code>list(io)</code>-这被认为不太可取。</p>
<pre><code>>>> m_2 = file_like_io.readlines()
</code></pre>
<p>我们可以看到我们的结果是一样的:</p>
<pre><code>>>> m_1==m_2
True
</code></pre>
<p>请记住,它是在换行符之后拆分的,同时也将它们保留在文本中,因此每打印一行将得到两个换行符,打印时为两倍间距。</p>