49

I have an numpy array of form

a = [1,2,3]

which I want to save to a .txt file such that the file looks like:

1 2 3

If I use numpy.savetxt then I get a file like:

1
2
3

There should be a easy solution to this I suppose, any suggestions?

Hooked
  • 84,485
  • 43
  • 192
  • 261
Palle
  • 493
  • 1
  • 4
  • 4

9 Answers9

53

If numpy >= 1.5, you can do:

# note that the filename is enclosed with double quotes,
# example "filename.txt"

numpy.savetxt("filename", a, newline=" ")

Edit

several 1D arrays with same length

a = numpy.array([1,2,3])
b = numpy.array([4,5,6])
numpy.savetxt(filename, (a,b), fmt="%d")

# gives:
# 1 2 3
# 4 5 6

several 1D arrays with variable length

a = numpy.array([1,2,3])
b = numpy.array([4,5])

with open(filename,"w") as f:
    f.write("\n".join(" ".join(map(str, x)) for x in (a,b)))

# gives:
# 1 2 3
# 4 5
kRazzy R
  • 1,561
  • 1
  • 16
  • 44
Avaris
  • 35,883
  • 7
  • 81
  • 72
  • What if a new identical array is to be added to the file, at next row. How to break the line first line and continue on the second line? – Palle Mar 05 '12 at 16:46
  • 1
    @PatrikT: If you have more than one 1D arrays you can just do `numpy.savetxt(filename,(a,b,c))`. It saves row wise. But they should have same size. – Avaris Mar 05 '12 at 20:03
  • What if e.g. a is shorter than b and c? How do I save these 3 arrays row wise? – Palle Mar 07 '12 at 13:03
  • 1
    @PatrikT: If you have variable length arrays, `savetxt` is not much of help. It is possible to do but it gets uglier and beats the purpose I think. Just write them normally as [BioGeek](http://stackoverflow.com/a/9565547/843822) suggested in a loop. I'll edit my answer to include all those alternatives. – Avaris Mar 07 '12 at 20:25
  • `newline=" "` will result in a trailing delimiter (space), which some programs don't accept (there must be strictly a new line at the end of the printing, rather than a space and then a new line). – Serge Rogatch Oct 23 '22 at 05:34
26

An alternative answer is to reshape the array so that it has dimensions (1, N) like so:

savetext(filename, a.reshape(1, a.shape[0]))
Hooked
  • 84,485
  • 43
  • 192
  • 261
  • This is exactly what you need if you're dumping readings into a file where every reading is made up of N samples. Perfect answer. – MedoAlmasry May 11 '20 at 00:24
9
import numpy
a = numpy.array([1,2,3])

with open(r'test.txt', 'w') as f:
    f.write(" ".join(map(str, a)))
BioGeek
  • 21,897
  • 23
  • 83
  • 145
6

I found that the first solution in the accepted answer to be problematic for cases where the newline character is still required. The easiest solution to the problem was doing this:

numpy.savetxt(filename, [a], delimiter='\t')
omegamanda
  • 388
  • 3
  • 7
3
import numpy as np

a = [1,2,3]    
b = np.array(a).reshape((1,3))    
np.savetxt('a.txt',b,fmt='%d')
Keyur Potdar
  • 7,158
  • 6
  • 25
  • 40
Innis
  • 31
  • 2
3

I know this is old, but none of these answers solved the root problem of numpy not saving the array row-wise. I found that this one liner did the trick for me:

b = np.matrix(a)
np.savetxt("file", b)
corym
  • 382
  • 1
  • 4
  • 14
1

Very very easy: [1,2,3]

A list is like a column.

1
2
3

If you want a list like a row, double corchete:

[[1, 2, 3]]  --->    1, 2, 3

and

[[1, 2, 3], [4, 5, 6]]  ---> 1, 2, 3
                             4, 5, 6

Finally:

np.savetxt("file", [['r1c1', 'r1c2'], ['r2c1', 'r2c2']], delimiter=';', fmt='%s')

Note, the comma between square brackets, inner list are elements of the outer list

Matt C
  • 4,470
  • 5
  • 26
  • 44
McKinley
  • 39
  • 1
  • 3
0

The numpy.savetxt() method has several parameters which are worth noting:

fmt : str or sequence of strs, optional
    it is used to format the numbers in the array, see the doc for details on formating

delimiter : str, optional
    String or character separating columns

newline : str, optional
    String or character separating lines.

Let's take an example. I have an array of size (M, N), which consists of integer numbers in the range (0, 255). To save the array row-wise and show it nicely, we can use the following code:

import numpy as np

np.savetxt("my_array.txt", my_array, fmt="%4d", delimiter=",", newline="\n")
jdhao
  • 24,001
  • 18
  • 134
  • 273
-1

just

' '.join(a)

and write this output to a file.

neizod
  • 1,582
  • 15
  • 24