Saving numpy array to txt file row wise Saving numpy array to txt file row wise python python

Saving numpy array to txt file row wise


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


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


import numpya = numpy.array([1,2,3])with open(r'test.txt', 'w') as f:    f.write(" ".join(map(str, a)))