[英]writing an array to disk in python
我從terminal interpreter
基本上將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])
我試圖將其寫入磁盤,並附加了minimum.py as(如此處所示 ):
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
您正在使用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 open('3fit','w') as outfile:
outfile.write(str(popt))
另外,您可能無法直接編寫np.array,所以我使用了str()函數。
這是語法上的簡單錯誤。
你真的想要:
with ('3fit','w') as outfile:
outfile.write(popt)
這里的with
語句調用了Python官方文檔中提到的context manager
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.