用python将数组写入磁盘

2024-04-29 12:28:05 发布

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

我用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的值可通过以下方式获得:

^{pr2}$

我试着把它写在磁盘上,把最小.pyas(如给定的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机器上,使用python3.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

Tags: 文件pyimportasnparrayoutfilefit
3条回答

打开文件时,必须使用open函数,“file”不存在。按如下方式修改该行:

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

另外,你可能不能写np.数组所以我直接使用str()函数。在

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

你真的想要:

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

这里的with语句正在调用context manager,如official Python documentation中所述。在

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

此外,您只能编写字符串。那么您希望如何将popt精确地表示为字符串?如果您希望获得与控制台上相同的输出,repr()将执行以下操作:

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

或者你可以写下数值,用空格隔开:

^{pr2}$

相关问题 更多 >