List of tab delimited arrays to numpy array?
<p>Win 7, x64, Python 2.7.12</p>

<p>I have data in the form</p>

<pre><code>myData = [[a1, b1, c1, d1, e1, f1, g1, h1], [a2, b2, c2, .... ], ..... ]
</code></pre>

<p>where <code>myData</code> is a <code>np.ndarray</code> of floats. I saved this by using the following...</p>

<pre><code>with open('myData.txt', 'w') as f:
    for s in myData:
        f.write(str(s) + '\n')
</code></pre>

<p>Which on inspection was actually saved like...</p>

<pre><code>[a1   b1   c1   d1   e1   f1   g1   h1]
[a2   b2   c2   d2   e2   f2   g2   h1]
.....
</code></pre>

<p>i.e. tab delimited.</p>

<p>So I tried to read it back in using...</p>

<pre><code>import numpy as np
from ast import literal_eval

with open('myData.txt', 'r') as f:
    fromFile = [np.ndarray(literal_eval(line)) for line in f]
f.close()
</code></pre>

<p>But this throws an error...</p>

<pre><code>  File "&lt;unknown&gt;", line 1
    [ 1.     1.198  2.063  1.833  1.458  1.885  1.969  0.343]
                 ^
SyntaxError: invalid syntax
</code></pre>

<p>So given that I cant regenerate the file <code>myData.txt</code> how do restore it to its initial data type?</p>

<p>Also is there a way of stopping the data being written out like that in the first place?</p>

<p>EDIT: A solution to the above...</p>

<pre><code>import numpy as np
from ast import literal_eval

branches = ['[ 1.     1.198  2.063  1.833  1.458  1.885  1.969  0.343]\n', 
            '[ 2.    1.26  2.    1.26  1.26  2.    1.26  0.  ]\n', 
            '[ 3.     1.688  2.     1.781  1.573  2.021  1.979  0.23 ]\n', 
            '[ 4.     1.604  2.729  1.792  1.667  2.49   1.948  0.293]\n']

branches = [line.rstrip(']\n') for line in branches]
branches = [line.lstrip('[ ') for line in branches]
print branches[0]

branches = [line.split('  ') for line in branches]
newBranches = []
for branch in branches:
    branch = filter(None, branch)
    branch = [float(item) for item in branch]
    newBranches.append(branch)

print newBranches[0]

branches = np.array(newBranches)
</code></pre>

<p>Unless there is a faster way of doing this then thats how I'll be doing it. I will also be taking Nils Werner's advice below in the answers.</p>

<p>You should use</p>

<pre><code>numpy.save('myData.npy', myData)
</code></pre>

<p>which you can then read like</p>

<pre><code>myData = numpy.load('myData.npy')
</code></pre>

python arrays numpy multidimensional-array