Python Practice › NumPy Programs › Program 81
Save an array to CSV
Write a NumPy program to save an array to a CSV file.
Output
a,b,c 1,2,3 4,5,6
Approach
np.savetxtwithdelimiter=",".
Solution
import numpy as npa = np.array([[1, 2, 3], [4, 5, 6]])np.savetxt("data.csv", a, delimiter=",", fmt="%d", header="a,b,c", comments="")print(open("data.csv").read())Output
a,b,c 1,2,3 4,5,6
Line by line
Line 3
fmt="%d" writes integers; comments="" stops NumPy putting “# ” before the header.
Learn the concept
New to this topic? Read the lesson, then come back.