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?
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With