0

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.

2
  • 2
    What does a = np.reshape(a, (-1, 8)) do? If it doesn't throw errors, save that. Commented May 1, 2018 at 18:55
  • Do you have to do it exclusively using numpy? Commented May 1, 2018 at 19:06

2 Answers 2

1
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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.