Python纹

2024-04-23 13:57:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Python 3.2.1,无法导入StringIO模块。我用 io.StringIO并且它可以工作,但是我不能将它与numpygenfromtxt一起使用,就像这样:

x="1 3\n 4.5 8"        
numpy.genfromtxt(io.StringIO(x))

我得到以下错误:

TypeError: Can't convert 'bytes' object to str implicitly  

当我写import StringIO的时候

ImportError: No module named 'StringIO'

Tags: 模块toioimportnumpyconvertbytesobject
3条回答

when i write import StringIO it says there is no such module.

来自What’s New In Python 3.0

The StringIO and cStringIO modules are gone. Instead, import the io module and use io.StringIO or io.BytesIO for text and data respectively.

是的。


修复某些Python2代码以使其在Python3中也能工作的一种可能有用的方法(警告清空器):

try:
    from StringIO import StringIO ## for Python 2
except ImportError:
    from io import StringIO ## for Python 3

Note: This example may be tangential to the main issue of the question and is included only as something to consider when generically addressing the missing StringIO module. For a more direct solution the the message TypeError: Can't convert 'bytes' object to str implicitly, see this answer.

在Python 3上,numpy.genfromtxt需要字节流。使用以下选项:

numpy.genfromtxt(io.BytesIO(x.encode()))

在我的案例中,我使用了:

from io import StringIO

相关问题 更多 >