Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving numpy array to txt file row wise

Tags:

python

save

numpy

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?

like image 386
Palle Avatar asked Mar 05 '12 10:03

Palle


People also ask

How do I save a NumPy array in a text file?

Let us see how to save a numpy array to a text file. Creating a text file using the in-built open() function and then converting the array into string and writing it into the text file using the write() function. Finally closing the file using close() function.

How do I save an array of data in a text file?

We can save an array to a text file using the numpy. savetxt() function. The function accepts several parameters, including the name of the file, the format, encoding format, delimiters separating the columns, the header, the footer, and comments accompanying the file.


1 Answers

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 
like image 68
Avaris Avatar answered Sep 28 '22 11:09

Avaris