Zohim Chandani
Zohim Chandani

Reputation: 29

numpy.loadtxt to load a file

I have a file which looks like this:

(The full version can be accessed here: https://drive.google.com/file/d/1uKRgp6X6ZfQbUsEr2bQ3_ZOPZYFSjmhj/view?usp=sharing)


[[51, 49, array([[ 67.,   0.,   0.,   0.],
       [  1.,  47.,   0.,   0.],
       [117.,   0.,   0.,   0.],
       [ 10., 126., 109.,   0.],
       [  7.,   0.,   0.,   0.],
       [ 90.,  50.,   0.,   0.],
       [ 50.,   0.,   0.,   0.],
       [  4.,  69.,  40.,  49.]])], 
[70, 49, array([[ 63.,   0.,   0.,   0.],
       [127.,  48.,   0.,   0.],
       [118.,   0.,   0.,   0.],
       [ 52., 125.,  68.,   0.],
       [  2.,   0.,   0.,   0.],
       [ 62., 102.,   0.,   0.],
       [ 84.,   0.,   0.,   0.],
       [ 58.,  89.,   5.,  72.]])],
[75, 49, array([[122.,   0.,   0.,   0.],
       [120., 104.,   0.,   0.],
       [ 86.,   0.,   0.,   0.],
       [104.,  24.,  15.,   0.],
       [ 99.,   0.,   0.,   0.],
       [ 77.,  41.,   0.,   0.],
       [124.,   0.,   0.,   0.],
       [126.,  37.,  73.,  59.]])]

where the headings are iteration = 51, value = 49, angles = array(...), iteration = 70... and so on.

How do I go about loading this in my script? Thanks.

Upvotes: 0

Views: 202

Answers (1)

Dominik Berse
Dominik Berse

Reputation: 308

The default numpy load methods wont work here, as the file does not have the expected format. If you are responsible for generating this file, consider using e.g. numpy.savetxt or numpy.save, so you can use numpy.loadtxt or numpy.load accordingly.

With the file you have, if the source can be trusted, a very quick and dirty solution would be to load this file using eval. However, consider reading on the the dangers of eval, as it can execute any code within that file.

Assuming you have imported numpy like this:

import numpy as np

this should work:

with open('filename.txt') as file:
    contents = file.read().replace('array', 'np.array')
    data = eval(contents)

Upvotes: 2

Related Questions