I would like to load the result of numpy.savetxt into a string. Essentially the following code without the intermediate file:
import numpy as np
def savetxts(arr):
np.savetxt('tmp', arr)
with open('tmp', 'rb') as f:
return f.read()
numpy.savetxt (fname, X, fmt='%.18e', delimiter=' ', newline=' ', header='', footer='', comments='# ', encoding=None) : This method is used to save an array to a text file. fname : If the filename ends in .gz, the file is automatically saved in compressed gzip format. loadtxt understands gzipped files transparently.
Mainly NumPy savetxt function is used to save arrays in txt format with different delimiters. NumPy savetxt function works with 1D and 2D arrays, the numpy savetxt also saves array elements in csv file format. Arrays play a major role in data science where speed matters.
Here we can use the header parameter in numpy.savetxt () function. This parameter indicates the input string can be written at the starting of the file. In this example, we have given the header value= “Integer values”. Once you will print ‘final_result’ then the output will display the values in the text file along with the header name.
You have to specify the format ( fmt) of you data in savetxt, in this case as a string ( %s ): The default format is a float, that is the reason it was expecting a float instead of a string and explains the error message. And what happens if I want to format the numbers? How can I give some format to the numbers only?
For Python 3.x you can use the io
module:
>>> import io
>>> s = io.BytesIO()
>>> np.savetxt(s, (1, 2, 3), '%.4f')
>>> s.getvalue()
b'1.0000\n2.0000\n3.0000\n'
>>> s.getvalue().decode()
'1.0000\n2.0000\n3.0000\n'
Note: I couldn't get io.StringIO()
to work. Any ideas?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With