2

I have a python list

temp = [['abc.jpg', 1, 2, 3, 'xyz'], ['def.jpg', 4,5,6, 'xyz']] 

To save it as an array, so I do this:

temp = np.vstack(temp)

Result:

print(temp)
temp = [['abc.jpg', '1', '2', '3', 'xyz'], ['def.jpg', '4','5','6', 'xyz']]

It is converting the integers to string. I dont want that to happen.

I want to save the result in a text file.

I tried the following:

np.savetxt("data.txt", temp)

But I get the following error:

TypeError: Mismatch between array dtype ('<U8') and format specifier ('%.18e %.18e %.18e %.18e %.18e %.18e')
Blue
  • 653
  • 1
  • 11
  • 26
  • A string array like this has to be saved with `%s` format. To retain more control on the display of numbers you need to create a structured array, which can be saved with `savetxt`. The `duplicate` sort-of helps with the structured array, but does not use `savetxt`. I'm sure there are newer better duplicates. – hpaulj Oct 31 '17 at 16:26

1 Answers1

2

try this(it saves every row separated by ";"):

 np.savetxt("data.txt", temp, delimiter=" ", newline = "\n", fmt="%s")
jimidime
  • 542
  • 3
  • 5
  • That gives a one line file with `abc.jpg 1 2 3 xyz;def.jpg 4 5 6 xyz;` – Bart Oct 31 '17 at 10:54
  • @Bart how do you want to save? – jimidime Oct 31 '17 at 10:54
  • np.savetxt("data.txt", temp, delimiter=" ", newline = "\n", fmt="%s") - this saves in new line. Works perfectly for me! Thanks – Blue Oct 31 '17 at 10:56
  • @Blue; which python/numpy/.. version? In my case (Python 3.6, Numpy 1.13) your solution does work (without converting `1` to `"1"`) – Bart Oct 31 '17 at 10:57
  • using 3.5.3 python version and 1.13.3 numpy version. I turned my list into an array with `temp = np.array(temp)`. Upon printing it I get `temp = [['abc.jpg', '1', '2', '3', 'xyz'], ['def.jpg', '4','5','6', 'xyz']]` but when I open the textfile there are no strings. It is saved as `abc.jpg 1 2 3 xyz def.jpg 4 5 6 xyz` – Blue Oct 31 '17 at 11:00