Roman Shapovalov的代码应该在Python 3中工作。x以及Python 2.6/2.7。下面是完整的例子:
import io
import numpy
x = "1 3\n 4.5 8"
numpy.genfromtxt(io.BytesIO(x.encode()))
输出:
array([[ 1. , 3. ],
[ 4.5, 8. ]])
Python 3.x的解释:
numpy。genfromtxt接受一个字节流(解释为字节而不是Unicode的类文件对象)。
io。BytesIO接受一个字节字符串并返回一个字节流。io。另一方面,StringIO将接受一个Unicode字符串并返回一个Unicode流。
x被赋值为一个字符串字面值,在Python 3中。x是一个Unicode字符串。
encode()获取Unicode字符串x并从中生成字节字符串,从而给出io. xml。BytesIO是一个有效的论点。
Python 2.6/2.7的唯一区别是x是一个字节字符串(假设不使用from __future__ import unicode_literals),然后encode()获取字节字符串x,并仍然从中生成相同的字节字符串。所以结果是一样的。
由于这是SO关于StringIO最流行的问题之一,这里有一些关于import语句和不同Python版本的更多解释。
以下是接受字符串并返回流的类:
io。BytesIO (Python 2.6, 2.7, and 3.x) -接受一个字节字符串。返回一个字节流。
io。StringIO (Python 2.6, 2.7,和3.x) -接受Unicode字符串。返回一个Unicode流。
StringIO。StringIO (Python 2.x) -接受字节字符串或Unicode字符串。如果是字节字符串,返回一个字节流。如果是Unicode字符串,返回一个Unicode流。
cStringIO。StringIO (Python 2.x) -更快版本的StringIO。StringIO,但不能接受包含非ascii字符的Unicode字符串。
注意StringIO。StringIO从StringIO导入StringIO,然后用作StringIO(…)。或者你导入StringIO,然后使用StringIO.StringIO(…)。模块名和类名恰好是相同的。它类似于datetime。
使用什么,取决于你支持的Python版本:
If you only support Python 3.x: Just use io.BytesIO or io.StringIO depending on what kind of data you're working with.
If you support both Python 2.6/2.7 and 3.x, or are trying to transition your code from 2.6/2.7 to 3.x: The easiest option is still to use io.BytesIO or io.StringIO. Although StringIO.StringIO is flexible and thus seems preferred for 2.6/2.7, that flexibility could mask bugs that will manifest in 3.x. For example, I had some code which used StringIO.StringIO or io.StringIO depending on Python version, but I was actually passing a byte string, so when I got around to testing it in Python 3.x it failed and had to be fixed.
Another advantage of using io.StringIO is the support for universal newlines. If you pass the keyword argument newline='' into io.StringIO, it will be able to split lines on any of \n, \r\n, or \r. I found that StringIO.StringIO would trip up on \r in particular.
Note that if you import BytesIO or StringIO from six, you get StringIO.StringIO in Python 2.x and the appropriate class from io in Python 3.x. If you agree with my previous paragraphs' assessment, this is actually one case where you should avoid six and just import from io instead.
If you support Python 2.5 or lower and 3.x: You'll need StringIO.StringIO for 2.5 or lower, so you might as well use six. But realize that it's generally very difficult to support both 2.5 and 3.x, so you should consider bumping your lowest supported version to 2.6 if at all possible.