Firstly is there a way to turn a string into an array?
I'm looking for a way to turn this:
['[[ 18.41978673]\n', ' [ 0.34748864]\n', ' [ -9.55729142]]']
back into
[[ 18.41978673]
[ 0.34748864]
[ -9.55729142]]
Secondly, is there a was to store the array as an array in a .txt file without having to turn it into a string in the first place?
This is the current method I have been using to put them into storage:
def add_to_file(self, weights):
path = 'C:/Users\PycharmProjects\project Current'
file = open(path, 'w')
file.write(weights)
file.close()
add_to_file(str(synaptic_weights))
When trying to do it the following way:
add_to_file(synaptic_weights)
I have this return in the console:
TypeError: write() argument must be str, not numpy.ndarray
The file type doesn't have to be .txt. If there is a better way to store arrays I am all ears.
3 Answers 3
Since you're using a Numpy array, an easy solution to save the array is:
np.savetxt(file_name, my_array)
then:
my_array = np.loadtxt(file_name)
1 Comment
np.savetxt, not np.savetext.You'll need to jump through a few hoops, but you can do it with json.loads and re.sub. This is the first step to salvaging your data and storing it in a usable form.
import json
import re
data = json.loads(re.sub(r"'|\\n", '', str(l)))[0]
print(data)
# [[18.41978673], [0.34748864], [-9.55729142]]
Now that you've salvaged your data, you can look at some options for saving to a file.
One option (probably the best) is using np.save:
np.save('data.npy', data)
Alternatives include either json.dump or pickle.dump. This would work:
import json
json.dump(data, open('data.json', 'w'))
Or, with pickle:
import pickle
pickle.dump(data, open('data.pkl', 'wb'))
serializingdocs.python.org/2/library/pickle.htmlnumpy.save