在python中将数组写入磁盘

时间:2014-03-18 09:47:36

标签: python arrays

我基本上使用python作为计算器,来自terminal interpreter。但是,对于特定的工作,我需要将其写为.py文件并将其结果保存到文件中。

对于我的真正问题,我提出的代码是:

#least.py program
import numpy as np
from scipy.optimize import curve_fit
xdata = np.array([0.1639534, 0.2411005, 0.3130353, 0.3788510,  0.4381247, 0.5373147, 0.6135673, 0.6716365, 0.7506711,  0.8000908, 0.9000000])
ydata =np.array ([7.1257999E-04,9.6610998E-04,1.1894000E-03,1.3777000E-03,1.5285000E-03,1.7297000E-03,1.8226000E-03,1.8422999E-03,1.7741000E-03,1.6574000E-03,1.1877000E-03])

def func (x,a,b,c):
    return a+b*x+c*x**3
popt, pcov =curve_fit(func,xdata,ydata,p0=(1,1,1))

并尝试将它们写入磁盘。

从终端开始,popt,pcov的值只能通过以下方式获得:

>>> popt
array([ -5.20906980e-05,   4.41458412e-03,  -3.65246935e-03])

我尝试将其写入磁盘,将least.py附加为(如here所示):

with file('3fit','w') as outfile:
    outfile.write(popt)

给了我错误:

Traceback (most recent call last):
  File "least.py", line 9, in <module>
    with file('3fit','w') as outfile:
NameError: name 'file' is not defined

请帮助。 我在linux机器上,使用python 3.3

print (sys.version)
3.3.5 (default, Mar 10 2014, 03:21:31) 
[GCC 4.8.2 20140206 (prerelease)]

修改 我希望列中的这些数据为:

-5.20906980e-05   
 4.41458412e-03  
-3.65246935e-03

3 个答案:

答案 0 :(得分:3)

您正在使用Python3,其中file()不再是一个函数。请改用open()

此外,您只能编写字符串。那么你想如何将popt完全表示为字符串?如果您想获得与控制台上相同的输出,repr()将执行:

with open('3fit', 'w') as outfile:
    outfile.write(repr(popt))

或者你可以写下由空格分隔的数值:

with open('3fit', 'w') as outfile:
    outfile.write(' '.join(str(val) for val in popt))

答案 1 :(得分:0)

打开文件时,您必须使用打开的功能,&#39;文件&#39;不存在。修改如下所示的行:

with open('3fit','w') as outfile:
    outfile.write(str(popt))

另外,您可能无法直接编写np.array,因此我使用了str()函数。

答案 2 :(得分:0)

这是语法上的一个简单错误。

你真的想要:

with ('3fit','w') as outfile:
    outfile.write(popt)

此处的with声明正在调用official Python documentation中提及的context manager