Saving numpy array to txt file row wise

Palle picture Palle · Mar 5, 2012 · Viewed 100.1k times · Source

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?

Answer

Avaris picture Avaris · Mar 5, 2012

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