How to Save an Array to a File in Python (Text, CSV, JSON, NPY)

When you’re working with arrays in Python, at some point you need to save them to a file: maybe to load them later, share them with a teammate, or feed them into a machine learning pipeline. In this tutorial, I’ll walk through how I usually save arrays and lists to files using Python in different formats: plain text, CSV, JSON, and efficient NumPy formats like .npy and .npz.

I’ll keep things beginner‑friendly, use simple examples (with US‑style data), and show both how to save and how to load the data back.

Prerequisites and Types of “Arrays” in Python

In Python, “array” can mean a few different things. Before saving to a file, it helps to know what you’re actually working with.

You’ll most often see:

  • A regular Python list: scores = [95, 88, 76, 90]
  • An array.array from the standard library (fixed type):
    from array import array
  • A NumPy array: import numpy as np

Here’s a quick side‑by‑side example:

# Built-in list
scores_list = [95, 88, 76, 90]

# array.array (integer array)
from array import array
scores_array = array("i", [95, 88, 76, 90])

# NumPy array
import numpy as np
scores_np = np.array([95, 88, 76, 90])

The way you save the data depends on which of these you’re using and what you want to do with the file later.

Save a Python List or array.array to a Text File

Let me start with the simplest case: you have a list of numbers (or an array.array) and want to write them to a plain text file.

One value per line (simple numeric list)

This is a good pattern for quick debugging or small datasets.

scores = [95, 88, 76, 90]

with open("scores.txt", "w") as f:
for score in scores:
f.write(str(score) + "\n")

This creates a file scores.txt that looks like:

95
88
76
90

To read it back into a list:

loaded_scores = []
with open("scores.txt", "r") as f:
for line in f:
loaded_scores.append(int(line.strip()))

print(loaded_scores) # [95, 88, 76, 90]

You can refer to the screenshot below to see the output.

How to Save an Array to a File Python

You can do the same with array.array by converting to str when writing, and back to int or float when reading.

Saving a 2D list (rows and columns)

Suppose you have a list of [month, sales] pairs for a US branch:

sales_data = [
["January", 12000],
["February", 13500],
["March", 15000],
]

You can save it as plain text using a simple separator like a space or comma:

sales_data = [
["January", 12000],
["February", 13500],
["March", 15000],
]

with open("sales.txt", "w") as f:
for month, amount in sales_data:
f.write(f"{month} {amount}\n")

Reading back:

loaded_sales = []
with open("sales.txt", "r") as f:
for line in f:
month, amount = line.strip().split()
loaded_sales.append([month, int(amount)])

print(loaded_sales)

Text files are:

  • Easy to inspect with any editor.
  • Simple to work with for small, structured data.

For spreadsheets, though, CSV is usually better.

Save an Array to a CSV File

CSV is ideal when you want to open the data in Excel, Google Sheets, or a BI tool.

Save a 2D list to CSV

Let’s say you have monthly sales by region in the US:

import csv

sales = [
["region", "month", "amount"],
["North", "January", 12000],
["South", "January", 9000],
["West", "January", 15000],
]

with open("sales.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(sales)

A couple of important points:

  • I use newline="" on Windows to avoid blank lines in the file.
  • writer.writerows writes all rows at once.

Reading the CSV back:

import csv

with open("sales.csv", "r", newline="") as f:
reader = csv.reader(f)
sales_loaded = list(reader)

print(sales_loaded)

You can convert numeric columns back to int or float if needed.

CSV from a NumPy array

If you have a NumPy array of numbers, you can either use csv.writer as above, or use NumPy’s savetxt (I’ll show savetxt a bit later).

Save a List or Array as JSON

JSON is great when:

  • You have nested lists or dictionaries.
  • You want to exchange data with web APIs or other services.
  • You want a human‑readable format that still preserves structure.

Save a list of numbers to JSON

import json

scores = [95, 88, 76, 90]

with open("scores.json", "w") as f:
json.dump(scores, f)

Load it back:

import json

with open("scores.json", "r") as f:
loaded_scores = json.load(f)

print(loaded_scores) # [95, 88, 76, 90]

Save a list of dictionaries

For example, student records from a US school:

import json

students = [
{"name": "Alice", "state": "CA", "gpa": 3.8},
{"name": "Bob", "state": "TX", "gpa": 3.4},
{"name": "Charlie", "state": "NY", "gpa": 3.9},
]

with open("students.json", "w") as f:
json.dump(students, f, indent=4)

Adding indent=4 makes the file easier to read.

Loading:

import json

with open("students.json", "r") as f:
loaded_students = json.load(f)

print(loaded_students)

One thing to keep in mind: JSON handles basic types (numbers, strings, lists, dicts) well, but it doesn’t directly support NumPy arrays. For NumPy, dedicated functions are much better.

Save a NumPy Array to a Binary .npy File

If you’re doing machine learning or numerical work, this is usually the best choice for saving arrays. It preserves:

Save a single array with np.save

import numpy as np

arr = np.array([[1.5, 2.0, 3.2],
[4.1, 5.3, 6.7]])

np.save("data.npy", arr)

This creates a binary file data.npy.

Load it back:

import numpy as np

loaded_arr = np.load("data.npy")
print(loaded_arr)
print(loaded_arr.shape)
print(loaded_arr.dtype)

You can refer to the screenshot below to see the output.

Save an Array to a File in Python

This is the standard pattern when you want to quickly save intermediate results in an ML or data science workflow.

Save Multiple NumPy Arrays With .npz

If you have several arrays that belong together (train/test splits, features/labels, etc.), you can store them in a single .npz file.

Save with np.savez

import numpy as np

train_data = np.random.rand(100, 10)
test_data = np.random.rand(20, 10)
labels = np.random.randint(0, 2, size=(100,))

np.savez("dataset.npz", train=train_data, test=test_data, labels=labels)

Load them back:

import numpy as np

data = np.load("dataset.npz")

train_loaded = data["train"]
test_loaded = data["test"]
labels_loaded = data["labels"]

print(train_loaded.shape) # (100, 10)
print(test_loaded.shape) # (20, 10)
print(labels_loaded.shape) # (100,)

If file size is a concern, you can use np.savez_compressed instead, which compresses the data at the cost of a bit more CPU time.

Save a NumPy Array to a Text File With savetxt

Sometimes you want a human‑readable text file while still working with NumPy. savetxt is built for that.

Basic savetxt example

import numpy as np

arr = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])

np.savetxt("array.txt", arr, fmt="%d", delimiter=",")

This writes:

1,2,3
4,5,6
7,8,9

You can refer to the screenshot below to see the output.

Save an Python Array to a File

Load it back with loadtxt:

import numpy as np

loaded = np.loadtxt("array.txt", delimiter=",", dtype=int)
print(loaded)
print(loaded.shape)

A few tips:

  • Use fmt for controlling the formatting (e.g., "%.4f" for floats).
  • For very large arrays, .npy is usually better in terms of speed and file size.

Which Format Should I Use?

Here’s how I usually decide:

Goal / ScenarioFormat I prefer
Quick debug, small listPlain text
Open in Excel or Google SheetsCSV
Share structured data (e.g., records)JSON
Save ML / numeric data (NumPy arrays).npy / .npz
Human‑readable numeric array (NumPy)savetxt (text)

If you’re unsure and working with NumPy, .npy is a safe default.

Common Mistakes and How to Avoid Them

Let me call out a few issues I see a lot, especially with beginners.

1. Use the wrong file mode (text vs binary)

If you use open(“file”, “w”) for something that expects binary, you’ll run into trouble. With NumPy’s np.save, you don’t need to worry about modes because it handles the file opening for you, but for lower‑level code:

  • Use "w" / "r" for text.
  • Use "wb" / "rb" for binary.

When in doubt, check the function’s documentation and examples.

2. Forgetting to use with open(…)

Always using a with block saves you from having to close files manually:

with open("data.txt", "w") as f:
f.write("Hello")

This pattern is safer and avoids subtle bugs where files stay open.

3. Overwriting files by accident

Both open(“file”, “w”) and np.save(“file.npy”, arr) will overwrite an existing file with the same name. If you need to keep previous versions, add a timestamp or version number to the filename:

import time

timestamp = int(time.time())
filename = f"data_{timestamp}.npy"
np.save(filename, arr)

4. JSON with unsupported types

JSON doesn’t know how to handle everything. If you call json.dump directly on a NumPy array, you’ll likely get an error or a list that doesn’t round‑trip cleanly.

If you really want JSON for a NumPy array, convert to a Python list first:

import json
import numpy as np

arr = np.array([1, 2, 3])

with open("array.json", "w") as f:
json.dump(arr.tolist(), f)

But for serious numerical work, .npy is still a better fit.

Best Practices for Saving Arrays to Files

Here are a few habits that have helped me (and students I’ve worked with):

  • Use with open(…) for all manual file I/O.
  • Stick to .npy / .npz for large numeric arrays in ML and data science projects.
  • Use CSV for sharing tabular data with non‑Python users.
  • Use JSON for configuration and structured, mostly text/number data.
  • Keep file paths configurable (for example, using environment variables or a config file) instead of hardcoding everything.
  • Add a simple confirmation message when debugging, like print(“Saved to data.npy”), so you’re sure the write happened.

Quick Practice Exercises

If you want to test yourself, try these:

  • Save a list of five US cities to a text file, one city per line, then read them back into a list.
  • Create a 2D NumPy array of shape (5, 3) with random integers, save it to scores.npy, and load it in a new script.
  • Create a list of dictionaries representing US customers (namestatespend), save it to customers.json, and load it back.

If you can do these comfortably, you’ve got the core patterns down.

FAQs

How do I save a NumPy array to a file in Python?

The simplest way is:
import numpy as np arr = np.array([1, 2, 3]) np.save(“array.npy”, arr)
Then load it with np.load(“array.npy”).

How do I save multiple NumPy arrays in one file?

Use np.savez or np.savez_compressed:
pythonnp.savez(“arrays.npz”, a=arr1, b=arr2)
Then:
data = np.load(“arrays.npz”)
arr1_loaded = data[“a”]
arr2_loaded = data[“b”]

How do I save a list of lists to a CSV file?

Use the csv module:
import csv

rows = [
[“name”, “state”],
[“Alice”, “CA”],
[“Bob”, “TX”],
]

with open(“people.csv”, “w”, newline=””) as f:
writer = csv.writer(f)
writer.writerows(rows)

What is the difference between np.save and np.savetxt?

np.save writes a binary .npy file that preserves dtype and shape exactly.
np.savetxt writes a human‑readable text file and is best for simple numeric arrays.

How do I choose between CSV, JSON, and NPY?

Use CSV when you care about spreadsheets and simple tabular data.
Use JSON for structured records and configuration.
Use .npy / .npz for efficient storage of NumPy arrays, especially in ML workflows.

You may also read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.