Jimbo
Jimbo

Reputation: 494

Save list values in csv file with Python

I have a Python simple list like this one:

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]

I want to save it in a csv file that looks like this:

1,2,3,4,5,6,7,8
9,10,11,12,13,14,15,16

How can I do that? I tried:

np.savetxt('fname.csv', bbox_form, fmt='%d')

But I don't know how to write a new line only after 8 values.

Upvotes: 0

Views: 59

Answers (2)

Achu
Achu

Reputation: 272

col_num=8
row_num=len(a)/col_num
b=np.reshape(a, [row_num,col_num])
d=[','.join(map(str,c)) for c in b]
np.savetxt('fname.csv', d, fmt='%s')

This should work

Upvotes: 1

James Smith
James Smith

Reputation: 31

Numpy will save each "row" in your array to a line. If you want to save it to multiple lines, then you'll need to reshape your array.

Have a look here: https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html

Upvotes: 0

Related Questions