2

I'm aware that this may have been answered before but please check that other answers are relevant to this instance!

I'm writing an array to a file as a string so that it can be stored when my script isn't running and be accessed again easily when run. When I then read this string out of the file again it is automatically read as a string.

I can fix this with a for loop that iterates through the saved string and appends each entry to an empty array, but that seems like overkill - is it? Is there a better way to read a string and convert it to an array?

So... something like this runs the first time in order to generate an array and write it to a file as a string:

the_file = open('.the_file.txt', 'w')
the_array = [10, 20, 30, 40, 50]
the_file.write(str(the_array))
the_file.close()

The next time the code is run a different section of code gets run that is something like this:

the_file = open('.the_file.txt', 'r')
the_array = the_file.read()
the_file.close()

If I print the the_array variable and its type at this point I get:

[10, 20, 30, 40, 50]
<type 'str'>

So I follow the advice given in this similar question here and do:

the_array = np.asarray(the_array)

...and then print the the_array variable and its type at this point to check that this has worked, to get:

[10, 20, 30, 40, 50]
<type 'numpy.ndarray'>

But now when I run the rest of my code I get the error:

TypeError: iteration over a 0-d array

Traced back to this part of my code:

the_array = sorted(the_array, reverse=True)

Can anyone help me out here; why does python think that my array is 0-d?

1
  • 1
    np.asarray doesn't parse strings. Commented Apr 12, 2016 at 16:38

1 Answer 1

3

the_array = np.asarray(the_array) is creating an array with one element in it: your string "[10, 20, 30, 40, 50]". Rather than read your file in, if you import json and replace the_array = the_file.read() with the_array = json.load(the_file), you'll get a list instead and can easily convert it to a numpy array.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.