5

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.

evtoh
  • 444
  • 3
  • 10
  • 21
Rafat
  • 137
  • 1
  • 3
  • 12

5 Answers5

3

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.

John1024
  • 109,961
  • 14
  • 137
  • 171
1

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.

Roger Fan
  • 4,945
  • 31
  • 38
1

write expects an encoded byte array.

If you are still coding Python 2, you might use f.write('{:d}\n'.format(d)).

In Python 3, you can use the cleaner print(d, file=f) instead.

5gon12eder
  • 24,280
  • 5
  • 45
  • 92
1

Given you are working with Numpy may I suggest you take a look at Pandas. That package has a range of input/output functions/methods associated with its DataFrame (2D array), such as to_csv. You may easily read and write header information with these function and it will take care of the conversion from number to string and back again.

import pandas as pd

pd.DataFrame([d], columns=['Sum']).to_csv(open('test.dat', 'w'))
data_read_again = pd.read_csv('test.dat', index_col=0)
Finn Årup Nielsen
  • 6,130
  • 1
  • 33
  • 43
0

I cannot say exactly if the rest of the code is correct or not but I have noticed that you don't specify the file type in the code:

f = open('test','w')

If it's a .txt you are going for it should read:

f = open('test.txt','w')
tshepang
  • 12,111
  • 21
  • 91
  • 136