Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2008/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Numpy &引用;OSError:无法以二进制模式将对象数组写入文件";_Numpy_Scipy_Python 3.5 - Fatal编程技术网

Numpy &引用;OSError:无法以二进制模式将对象数组写入文件";

Numpy &引用;OSError:无法以二进制模式将对象数组写入文件";,numpy,scipy,python-3.5,Numpy,Scipy,Python 3.5,那一定是那种日子。我一直能够使用函数tofile来保存数据。但由于某种原因,今天它不起作用:) 获取以下结果: Traceback (most recent call last): File "C:/context.py", line 67, in <module> npdata.tofile('myfile.dat') OSError: cannot write object arrays to a file in binary mode <class 'list'>

那一定是那种日子。我一直能够使用函数tofile来保存数据。但由于某种原因,今天它不起作用:)

获取以下结果:

Traceback (most recent call last):
File "C:/context.py", line 67, in <module>
npdata.tofile('myfile.dat')
OSError: cannot write object arrays to a file in binary mode
<class 'list'>
<class 'numpy.ndarray'>
回溯(最近一次呼叫最后一次):
文件“C:/context.py”,第67行,在
npdata.tofile('myfile.dat')
OSError:无法以二进制模式将对象数组写入文件
它说我以二进制模式打开了文件。但据我所知,我并不是以二进制模式打开它

编辑(问题解决后):当我发布这个问题时,我假设blist是一个整数列表。相反,它是一个整数列表的列表。问题是,当我创建它时,我得到的是一个dtype=object,而不是我所期望的dtype=int32


士气:确保正确使用np.append/np.extend,并始终明确设置数据类型。

以二进制模式打开文件进行写入:

with open(filename, 'wb'):
    do stuff

让我知道这是否适合你

根据
tofile
docs,如果
sep
是默认值,则以二进制模式写入数组

In [714]: x
Out[714]: array([[1, 2, 3], [1, 2]], dtype=object)

In [715]: x.tofile('test')
---------------------------------------------------------------------------
OSError                                   Traceback (most recent call last)
<ipython-input-715-0ff8f3c688ad> in <module>()
----> 1 x.tofile('test')

OSError: cannot write object arrays to a file in binary mode
我有另一个包含生成器的对象数组(来自另一个问题)

In [719]: g.tofile('test',sep=',')

In [720]: cat test
<generator object <genexpr> at 0xb266632c>
[719]中的
:g.tofile('test',sep=','
In[720]:cat测试
因此,在
text
模式下,
tofile
将数组的
str(x)
表示形式写入文件


np.save
更擅长处理对象数组。它使用
pickle
将无法写入的对象编码为常规数组
np.load
可以重新加载这样的文件。

显示一些重现问题的示例数据。您是否需要
对象
数据类型?谢谢。你帮我发现了问题。我只是假设我有一个不同的数据类型。问题是blist实际上不是一个整数列表,而是一个列表列表,而np.array创建的是一个对象列表,而不是一个“int32”列表。所以当我在代码中创建blist时。我使用的是blist.append(),而应该使用blist.extend()。与我的
x
一样,如果子列表的长度不同,则数组是object dtype。如果它们的大小都匹配,
np.array
更倾向于将其设置为2d(或更高)。这很有趣,因为如果我的列表的大小都相同。我不可能抓住这个问题。但我的用户可能会抓到它。虽然我的用户是我明天。
In [716]: x.tofile('test',sep=',')

In [717]: cat test
[1, 2, 3],[1, 2]
In [719]: g.tofile('test',sep=',')

In [720]: cat test
<generator object <genexpr> at 0xb266632c>