Python Practice › NumPy Programs › Program 81

Save an array to CSV

EasyNumPy Programs · 81 of 100

Write a NumPy program to save an array to a CSV file.

Advertisement
Output
a,b,c
1,2,3
4,5,6

Approach

  1. np.savetxt with delimiter=",".

Solution

Python
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.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More numpy programs

← All 100 NumPy Programs