Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk4 min

How to Save a NumPy Array to a File in Python: Text, CSV, JSON, and NPY

Use NPY for NumPy round-trips, text or CSV for readable rows, and JSON for nested data. See working Python examples and the trade-offs of each format.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose the file format based on what you need to do with the array: use np.save and np.load for a NumPy-native round trip, np.savetxt for readable numeric text, CSV for tabular exchange, or JSON for nested application data. The examples below show how to write and read each format, plus the main fidelity and safety trade-offs.

Which format should you choose?

Format Best fit Main benefit Important trade-off
.npy One array that you will load back into NumPy NumPy’s binary format is designed for saving and loading arrays It is not intended to be human-readable text
.npz Several named arrays in one file Groups multiple arrays in one NumPy archive; an option is compressed Reading it requires NumPy-compatible software
Text or delimited text Inspection or simple numeric exchange Readable, with delimiter and formatting controls np.savetxt supports one- and two-dimensional arrays; text conversion choices matter
CSV Tabular exchange with spreadsheets or other tools Familiar rows and columns CSV does not retain NumPy dtype or shape metadata, and other programs may infer types differently
JSON Nested values used in application data or interchange Common text structure for nested data Convert the array to lists, and preserve or reapply dtype and shape explicitly if exact reconstruction matters

For durable NumPy-specific storage, prefer .npy or .npz over raw binary methods such as ndarray.tofile and np.fromfile. NumPy cautions that raw file I/O loses endianness and precision information. See NumPy’s file I/O guidance.

Save one array in NumPy’s binary format

Use np.save to write an array to an .npy file, then np.load to read it:

import numpy as np

arr = np.array([[1, 2], [3, 4]])
np.save("array.npy", arr)
restored = np.load("array.npy", allow_pickle=False)

If you pass a filename or path without the .npy extension, np.save appends it. The save API defaults to allow_pickle=True; set it to False when you do not need object arrays. See the NumPy save reference.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Pickle-enabled object arrays carry security and portability drawbacks. Do not load pickle-enabled files from untrusted sources. Keep the load setting compatible with the file you are opening, and use allow_pickle=False when object dtype is unnecessary; NumPy explains the risk in its I/O guidance.

Save several arrays in one archive

Use np.savez for an uncompressed archive or np.savez_compressed for its compressed counterpart. Supply names as keyword arguments so you can retrieve arrays by name:

np.savez("arrays.npz", first=arr, second=arr * 2)

with np.load("arrays.npz", allow_pickle=False) as data:
    first = data["first"]
    second = data["second"]

np.savez_compressed("arrays-compressed.npz", first=arr, second=arr * 2)

The archive APIs are listed in NumPy’s input and output reference.

Write readable text or numeric CSV

For a simple numeric matrix, np.savetxt writes text and accepts a delimiter. Use a matching delimiter when reading it back:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
np.savetxt("array.txt", arr)
np.savetxt("array.csv", arr, delimiter=",")
restored = np.loadtxt("array.csv", delimiter=",")

np.savetxt is documented for one- or two-dimensional arrays. Its formatting and delimiter options let you control the text representation, but text is not the same as preserving all NumPy array metadata. For data with missing values or more involved parsing needs, consider np.genfromtxt and choose its missing-value policy deliberately. See the NumPy I/O API index and file I/O guidance.

Use Python’s CSV module for general rows

When values need CSV quoting, may contain delimiters, or are irregular text rather than a simple numeric matrix, Python’s csv module is often a better fit:

import csv

with open("rows.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.writer(f)
    writer.writerows(arr.tolist())

When passed a file object, Python recommends opening it with newline="". The writer stringifies non-string values. On reading, csv.reader returns strings by default, so convert fields explicitly when you need numeric values. CSV dialects also differ between applications; confirm the delimiter, quoting, header, encoding, and line-ending expectations of the program that will read the file. See the Python CSV documentation.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Write an array as JSON

Python’s JSON encoder does not directly serialize a NumPy ndarray. Convert it to nested built-in Python lists with tolist(), then dump the result:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import json
import numpy as np

arr = np.array([[1, 2], [3, 4]])
with open("array.json", "w", encoding="utf-8") as f:
    json.dump(arr.tolist(), f)

with open("array.json", encoding="utf-8") as f:
    nested = json.load(f)
restored = np.array(nested)

json.load returns ordinary Python containers, not an ndarray. Reconstruct one with np.array when needed. If exact dtype or shape matters—particularly for empty arrays, unusual dtypes, or application-specific values—include that metadata in a documented schema and restore it deliberately. NumPy describes the list conversion approach in its file I/O guide; supported JSON value mappings are in the Python JSON documentation.

Python’s JSON encoder allows NaN and infinities by default, even though they are outside strict JSON. Set allow_nan=False if you want the encoder to raise ValueError for those values, and define the intended policy for non-finite numbers. Also, JSON is not a framed protocol: repeated calls to json.dump on the same file do not create one valid JSON document.

Handle large arrays and choose deliberately

For large .npy files, NumPy supports memory mapping through np.load(..., mmap_mode=...), which can provide access without reading the entire file into memory at once. Memory mapping is not chunking or compression. For exact behavior and mode options, consult NumPy’s I/O guide.

  • Choose .npy for one array that will be reused in NumPy.
  • Choose .npz to group named arrays.
  • Choose text or CSV when people or other tools need readable rows, and account for conversions and consumer-specific CSV rules.
  • Choose JSON for nested application data, converting with tolist() and documenting metadata or non-finite-number handling as needed.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.