How to write a CSV file with NumPy

CSV export lets a NumPy array leave a Python-only workflow and move into spreadsheet tools, text-based review, or another program that expects delimited rows. It works best when the data is already a rectangular numeric array and the receiving tool only needs values, column names, and a predictable delimiter.

The np.savetxt() function writes one-dimensional or two-dimensional arrays to a text file. For a CSV-style export, set the delimiter to a comma, choose a fmt string that matches the precision the receiver should see, and decide whether the header should be a normal first row or a commented line.

Use CSV for interchange and NPY or NPZ when another NumPy process must keep dtype and shape metadata. For mixed rows with text fields that can contain commas, quotes, or line breaks, use a CSV-aware writer such as Python's csv module instead of relying on np.savetxt() text formatting.

Steps to write a CSV file with NumPy:

  1. Create a script that writes a numeric array to a CSV file.
    csv-write.py
    import numpy as np
    from pathlib import Path
     
    path = Path("sensor-readings.csv")
    readings = np.array(
        [[18.25, 42.0, 0.98], [18.50, 41.5, 0.99], [18.75, 41.0, 1.01]],
        dtype=np.float64,
    )
     
    np.savetxt(
        path,
        readings,
        delimiter=",",
        header="temperature,humidity,calibration",
        comments="",
        fmt="%.2f",
    )
     
    print(path.read_text().strip())
     
    loaded = np.loadtxt(path, delimiter=",", skiprows=1)
    print("shape:", loaded.shape)
    print("dtype:", loaded.dtype)
    print("values match rounded export:", np.allclose(loaded, np.round(readings, 2)))

    comments=“” writes the header without the default # prefix. The fmt setting controls the text stored in the CSV file, so choose it before sharing the export.

  2. Run the script and verify the exported text and reload check.
    $ python3 csv-write.py
    temperature,humidity,calibration
    18.25,42.00,0.98
    18.50,41.50,0.99
    18.75,41.00,1.01
    shape: (3, 3)
    dtype: float64
    values match rounded export: True

    The shape check confirms that np.loadtxt() read three rows and three columns after skipping the header row.

  3. Remove the sample CSV file and script after testing.
    $ rm sensor-readings.csv csv-write.py

    Keep the CSV file instead when it is the export another tool or person should receive.