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

I do some calculations after reading the file and want to save the result (one number) to another file. I want to be able to do things with this file later. I'm having trouble saving the result in a 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 f.write(d) :

An asymmetric array cannot be interpreted as a character buffer

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

IndexError: tuple index out of range

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

+5
source share
5 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 then read it as a numpy array, use the pickle module.

+3
source

Try converting d to a string before writing it.

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

Also, pay attention to the use of the with context manager, which is recommended to be used when opening files.

+1
source

write expects a coded byte array.

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

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

+1
source

Given that you work with Numpy, I can suggest you take a look at Pandas. This package has a number of I / O functions / methods associated with its DataFrame (2D array), for example to_csv . You can easily read and write header information using these functions, and it will take care of converting from a number to a string and vice versa.

 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) 
+1
source

I cannot say for sure whether the rest of the code is correct or not, but I noticed that you are not specifying the file type in the code:

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

If this is the tag that you are going to use, it should read:

 f = open('test.txt','w') 
0
source

Source: https://habr.com/ru/post/1202454/


All Articles