Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write the result of a calculation to a file in python?

Tags:

python

output

I'm doing some calculations after reading a file, and want to store the result (a single number) to another file. I want to be able to do things with this file later. I'm having problems storing the result into the text file.

I tried this:

    c = fdata_arry[:,2]*fdata_arry[:,4] 
    d = np.sum(c)
    print d
    f = open('test','w')
    f.write(d) 
    f.close()

which gives me this error for the line f.write(d):

Non-character array cannot be interpreted as character buffer

I also tried using np.savetxt('test.dat',d) but that gives me:

IndexError: tuple index out of range

Any idea how can I solve this? Note that d is just a single value, which is the sum of a few numbers.

like image 260
Rafat Avatar asked Sep 12 '14 22:09

Rafat


2 Answers

To write to a file, python wants strings or bytes, not numbers. Try:

f.write('%s' % d)

or

f.write('{}'.format(d))

On the other hand, if you want to write a numpy array to a file and later read it back in as a numpy array, use the pickle module.

like image 107
John1024 Avatar answered Sep 22 '22 19:09

John1024


Try converting d to a string before writing it.

with open('test.txt', 'w') as f:
    f.write(str(d))

Also note the use of the with context manager, which is good practice to always use when opening files.

like image 31
Roger Fan Avatar answered Sep 22 '22 19:09

Roger Fan