1

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.

user812786
4,4306 gold badges42 silver badges50 bronze badges
asked Jul 27, 2017 at 8:13
2

3 Answers 3

2

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)
answered Jul 27, 2017 at 8:20
Sign up to request clarification or add additional context in comments.

1 Comment

There's a typo there, the function is called np.savetxt, not np.savetext.
1

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'))
answered Jul 27, 2017 at 8:16

2 Comments

Of course this works, but if he'd serialize it in the first place it would be much better.
@moritzg The list has not been stringified properly to begin with. If OP is to salvage anything, sooner or later, they'd need to do this.
1

I usually use

a = np.ones((3,3))
np.save('arr', a)
a2 = np.load('arr.npy')
print a2

See the documentation here: np.save, np.load

Panda
6,8846 gold badges46 silver badges61 bronze badges
answered Jul 27, 2017 at 8:42

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.