用python将数组写入磁盘
我使用用python将数组写入磁盘,python,arrays,Python,Arrays,我使用python基本上是作为计算器,从终端解释器。但是,对于特定的工作,我需要将其作为.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.61356
python
基本上是作为计算器,从终端解释器
。但是,对于特定的工作,我需要将其作为.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追加为(给定):
这给了我一个错误:
Traceback (most recent call last):
File "least.py", line 9, in <module>
with file('3fit','w') as outfile:
NameError: name 'file' is not defined
编辑
我希望这些数据列在一列中,如下所示:
-5.20906980e-05
4.41458412e-03
-3.65246935e-03
打开文件时,必须使用“打开”功能,“文件”不存在。修改行,如下所示:
with open('3fit','w') as outfile:
outfile.write(str(popt))
另外,您可能无法直接编写np.array,因此我使用了str()函数。打开文件时,必须使用open函数,“file”不存在。修改行,如下所示:
with open('3fit','w') as outfile:
outfile.write(str(popt))
另外,您可能无法直接编写np.array,因此我使用了str()函数。您使用的是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))
您正在使用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))
这是一个简单的语法错误 你真的想要:
with ('3fit','w') as outfile:
outfile.write(popt)
此处的
with
语句调用的是上下文管理器,如中所述。这是一个简单的语法错误
你真的想要:
with ('3fit','w') as outfile:
outfile.write(popt)
这里的with
语句调用的是一个上下文管理器
。中提到的,您必须将其写入.py文件的原因是什么?从二进制格式保存/获取它对您的用例不起作用吗?您必须将其写入.py文件的原因是什么?从二进制格式保存/获取它不起作用吗为您的用例工作?