在Python中将数组写入磁盘

0 投票
3 回答
884 浏览
提问于 2025-04-17 22:47

我基本上把 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 文件(就像在 这里 提到的那样):

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

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

你真正想要的是:

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

这里的 with 语句是在调用一个 上下文管理器,就像在官方Python文档中提到的那样。

0

在打开一个文件的时候,你需要使用open这个函数,因为'file'这个东西是不存在的。把那一行改成下面这样:

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

另外,你可能不能直接写你的np.array,所以我用了str()这个函数。

4

你正在使用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))

撰写回答