50

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?

1
  • 1
    Or you only dealing with 1D arrays? Commented Mar 5, 2012 at 11:05

9 Answers 9

54

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
Sign up to request clarification or add additional context in comments.

5 Comments

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?
@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.
What if e.g. a is shorter than b and c? How do I save these 3 arrays row wise?
@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 suggested in a loop. I'll edit my answer to include all those alternatives.
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).
27

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]))

1 Comment

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.
9
import numpy
a = numpy.array([1,2,3])

with open(r'test.txt', 'w') as f:
    f.write(" ".join(map(str, a)))

Comments

7

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')

Comments

5

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)

1 Comment

Would you explain "array row-wise"?
3
import numpy as np

a = [1,2,3]    
b = np.array(a).reshape((1,3))    
np.savetxt('a.txt',b,fmt='%d')

2 Comments

While this code-only answer may solve the problem at hand, more explanation is necessary to help future users of the site understand how to apply this solution to their situation.
Please add some explanation to your answer
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

Comments

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")

Comments

-1

just

' '.join(a)

and write this output to a file.

2 Comments

That will give a TypeError: sequence item 0: expected string, numpy.int32 found, so you must first convert to string before joining.
' '.join(str(x) for x in a)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.