savetxt and download

savetxt to /uploads, fmt, headers, and the workbench download chip.

Writes go to /uploads. After Run, click on the file chip. Prefer CSV for this course; np.save also creates a chip if you need a .npy.

Goal

Write a small report with a comment header, reload it, and see the download chip.

Write and read back

import os

revenue = np.array(
    [
        [126.0, 154.0, 62.0],
        [94.5, 132.0, 0.0],
        [31.5, 242.0, 31.0],
    ]
)
np.savetxt("revenue_grid.csv", revenue, delimiter=",", fmt="%.1f")
print("wrote revenue_grid.csv")
print(os.listdir("/uploads"))
print()
print(np.loadtxt("revenue_grid.csv", delimiter=","))

Comment header (skipped on load)

import os

# Nairobi, Mombasa, Kisumu — revenue total, Apr mm
report = np.array(
    [
        [342.0, 150.0],
        [226.5, 90.0],
        [304.5, 180.0],
    ]
)
np.savetxt(
    "city_report.csv",
    report,
    delimiter=",",
    fmt="%.1f",
    header="revenue,apr_mm  rows: Nairobi, Mombasa, Kisumu",
)
print(open("/uploads/city_report.csv").read())
print(np.loadtxt("city_report.csv", delimiter=","))

Default comments='#' prefixes the header so loadtxt skips it.

Optional binary

grid = np.arange(6, dtype=float).reshape(2, 3)
np.save("grid.npy", grid)
print(np.load("grid.npy"))

The .npy chip downloads like any other upload. Spreadsheet tools prefer the CSV from savetxt.

Tip

If no chip appears, print os.listdir("/uploads"). The filename must be a bare name such as out.csv, not a path outside /uploads.