0

I use python basically as a calculator, from terminal interpreter. But, for a particular work, I need to write it as .py file and save its result to a file.

For my real problem, the code I came up with is:

#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))

and trying to write them in disk.

As from terminal, the value of popt, pcov will simply available by:

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

I tried to write it in disk, appending the least.py as(as given here):

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

which gives me error:

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

Kindly help. I am in linux machine, using python 3.3

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

EDIT I would like those data in a column,as:

-5.20906980e-05   
 4.41458412e-03  
-3.65246935e-03
1
  • Is there a reason why you have to write it to a .py file -- does saving /fetching it from a binary format not work for your use case? Commented Mar 18, 2014 at 9:56

3 Answers 3

5

You are using Python3, where file() is not a function any more. Use open() instead.

Furthermore, you can only write strings. So how do you want to have popt represented as a string exactly? If you want to get the same output as on the console, repr() will do:

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

Or you could just write the numerical values, separated by blanks:

with open('3fit', 'w') as outfile:
    outfile.write(' '.join(str(val) for val in popt))
Sign up to request clarification or add additional context in comments.

Comments

1

This is a simple error in syntax.

You really want:

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

The with statement here is calling a context manager as mentioned in the official Python documentation.

Comments

0

When opening a file, you have to use the open function, 'file' doesn't exist. Modify the line as followed :

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

Plus, you probably can't write your np.array directly so I used the str() function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.