Reading & Writing Files
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
This page was checked in October 2026 against NumPy 2.5 (2.5.4 is the current patch release). Examples target Python 3.13 or 3.14 and were run on Python 3.13. Every example was run on NumPy 2.5.4.
NumPy reads and writes arrays in three families of formats: its own binary formats (.npy and .npz), delimited text, and raw bytes with no header. Which one to use depends on who will read the file: another NumPy program, a person, a spreadsheet, or a program in another language. For tabular data with headers, dates and missing values, pandas is usually the better reader (see Data Sources & File Formats); NumPy’s readers are best for numeric matrices and for arrays that must round-trip exactly.
The .npy and .npz formats
numpy.save writes one array to a .npy file. The file starts with a small header that records the dtype, the shape and the memory order, followed by the raw data, so numpy.load restores the array exactly, including dtype, byte order and structured fields. NumPy adds the .npy extension if the file name lacks it. The format is documented, versioned and stable across NumPy versions, which makes it suitable for long-lived files.
import numpy as np
a = np.arange(6, dtype="f8").reshape(2, 3)
np.save("a.npy", a)
print(np.load("a.npy"))
# in-memory buffers work too
import io
buf = io.BytesIO()
np.save(buf, a)
buf.seek(0)
print(np.load(buf).shape)
[[0. 1. 2.] [3. 4. 5.]] (2, 3)
Source: numpy.save and numpy.load
numpy.savez stores several arrays, by keyword name (or arr_0, arr_1, … for positional ones), in a single .npz file, which is an ordinary ZIP archive of .npy files. numpy.savez_compressed does the same with DEFLATE compression. Loading an .npz returns a lazy NpzFile, which reads an array only when you index it; use it as a context manager so the file is closed:
np.savez("bundle.npz", x=a, y=np.arange(3))
np.savez_compressed("bundle_c.npz", x=a, y=np.arange(3))
with np.load("bundle.npz") as data:
print(data.files) # ['x', 'y']
print(data["x"].shape) # (2, 3)
['x', 'y'] (2, 3)
Compression costs CPU time on both write and read and pays off for data with redundancy; random-looking floating point data barely compresses. Compressed members cannot be memory-mapped.
Source: numpy.savez and numpy.savez_compressed
The binary format specification, and the helper functions numpy.lib.format.read_magic, read_array_header_1_0 and open_memmap, are described in numpy.lib.format.
Pickle, object arrays and allow_pickle
Arrays with dtype=object cannot be stored as plain data, so NumPy falls back to Python pickle for them. Since NumPy 1.16.3 numpy.load defaults to allow_pickle=False, because unpickling a file from an untrusted source can execute arbitrary code. Without the flag, NumPy refuses object arrays in both directions:
o = np.array([{"a": 1}, None], dtype=object)
try:
np.save("o.npy", o, allow_pickle=False)
except ValueError as e:
print(e)
np.save("o.npy", o) # allowed: allow_pickle is True by default when saving
try:
np.load("o.npy")
except ValueError as e:
print(e)
Object arrays cannot be saved when allow_pickle=False Object arrays cannot be loaded when allow_pickle=False
Pass allow_pickle=True to np.load only for files you created or trust. If you need to share data between parties, use a numeric dtype, a structured array, or an interchange format such as Parquet or HDF5 instead of pickled objects.
Source: numpy.load: allow_pickle
Memory-mapping large files
With mmap_mode="r" (read-only), "r+" (read and write) or "c" (copy-on-write in memory), numpy.load returns a numpy.memmap instead of reading the data. The operating system pages data in on access, so you can slice a file larger than memory. numpy.lib.format.open_memmap creates a new .npy file that you fill through a memory map:
np.save("big.npy", np.arange(1_000_000, dtype="i4"))
m = np.load("big.npy", mmap_mode="r")
print(type(m).__name__, m[999_999])
mm = np.lib.format.open_memmap("new.npy", mode="w+", dtype="f4", shape=(4, 3))
mm[:] = 1
mm.flush()
print(np.load("new.npy").sum())
memmap 999999 12.0
Memory mapping works for .npy files and for headerless raw files through numpy.memmap, but not for .npz archives. Call flush() before relying on writes being on disk, and delete the memmap object before deleting the file on Windows.
Source: numpy.memmap
Text files: savetxt and loadtxt
numpy.savetxt writes a 1-D or 2-D array as delimited text. The fmt argument is a printf-style format (one for all columns or a list or sequence for each column), delimiter separates columns, and header, footer and comments add lines (the comments prefix, "# " by default, is put before each header line so a reader can skip them):
np.savetxt("t.csv", a, delimiter=",", fmt="%.2f", header="c0,c1,c2", comments="# ")
print(open("t.csv").read())
# c0,c1,c2 0.00,1.00,2.00 3.00,4.00,5.00
Source: numpy.savetxt
numpy.loadtxt is the fast reader for files in which every row has the same number of columns and no values are missing. Useful arguments are delimiter, skiprows, usecols, dtype (including structured dtypes), comments, converters (a function per column), max_rows, ndmin and encoding. A row with the wrong number of fields raises an error rather than being padded:
print(np.loadtxt("t.csv", delimiter=",")) # '# ' header ignored
print(np.loadtxt("t.csv", delimiter=",", skiprows=1, usecols=(0, 2)))
s = io.StringIO("# comment\n1;2,5\n3;4,5\n")
print(np.loadtxt(s, delimiter=";", converters={1: lambda v: float(v.replace(",", "."))}))
print(np.loadtxt(io.StringIO("a 1\nb 2"), dtype=[("k", "U1"), ("v", "i4")]))
try:
np.loadtxt(io.StringIO("1,2\n3\n"), delimiter=",")
except ValueError as e:
print(e)
[[0. 1. 2.]
[3. 4. 5.]]
[[0. 2.]
[3. 5.]]
[[1. 2.5]
[3. 4.5]]
[('a', 1) ('b', 2)]
the number of columns changed from 2 to 1 at row 2; use `usecols` to select a subset and avoid this error
loadtxt was rewritten in C in NumPy 1.23 and is much faster than the older Python implementation that older tutorials describe, and it gained a quotechar argument for quoted fields. It does not handle missing values, dates or mixed column types beyond a structured dtype: use genfromtxt or pandas for those.
Source: numpy.loadtxt and numpy.savetxt
Messy text: genfromtxt
numpy.genfromtxt runs two loops: it splits lines into values and converts each column. It can read column names from the first row (names=True), guess a dtype per column (dtype=None), skip header and footer lines, and replace missing or invalid entries with a filling_values default, or return a masked array (usemask=True):
s = io.StringIO("id,score,name\n1,0.5,ann\n2,,bob\n3,0.7,cy\n")
g = np.genfromtxt(s, delimiter=",", names=True, dtype=None, encoding="utf-8")
print(g.dtype)
print(g)
s.seek(0)
gm = np.genfromtxt(s, delimiter=",", names=True, dtype=None, encoding="utf-8", usemask=True)
print(gm["score"])
s.seek(0)
print(np.genfromtxt(s, delimiter=",", skip_header=1, usecols=(0, 1), filling_values=-1))
[('id', '<i8'), ('score', '<f8'), ('name', '<U3')]
[(1, 0.5, 'ann') (2, nan, 'bob') (3, 0.7, 'cy')]
[0.5 -- 0.7]
[[ 1. 0.5]
[ 2. -1. ]
[ 3. 0.7]]
With dtype=None the result is a one-dimensional structured array (see Structured Arrays) whose fields have the guessed types. Pass encoding="utf-8" explicitly: the default encoding=None uses the system locale encoding, so the same script can read a file differently on two machines, and the special value "bytes" returns text columns as byte strings. Other useful arguments are missing_values (strings to treat as missing, per column), converters, names as a list, excludelist, deletechars, case_sensitive and invalid_raise (set to False to skip rows with the wrong number of columns instead of failing). genfromtxt is slower than loadtxt.
Raw binary: tofile, fromfile and frombuffer
ndarray.tofile writes the array’s bytes with no header, and numpy.fromfile reads them back given an explicit dtype and optional count and offset. Neither stores shape or dtype, so the reader must know them, and neither is portable across machines of a different byte order unless you spell the byte order in the dtype ("<f8" little endian, ">f8" big endian). numpy.frombuffer makes an array over an existing bytes-like object without copying:
a.tofile("raw.bin")
print(np.fromfile("raw.bin", dtype="f8").reshape(2, 3))
print(np.frombuffer(a.tobytes(), dtype="f8"))
a.astype(">f8").tofile("be.bin")
print(np.fromfile("be.bin", dtype=">f8")[:3]) # correct
print(np.fromfile("be.bin", dtype="<f8")[:2]) # wrong byte order: garbage
[[0. 1. 2.] [3. 4. 5.]] [0. 1. 2. 3. 4. 5.] [0. 1. 2.] [0.00000e+000 3.03865e-319]
Use a structured dtype to read files of fixed-width records, with align=False for a packed record or align=True for a C struct with padding. fromfile and tofile require a real file object or path; for in-memory streams use frombuffer and tobytes. fromfile also has a text mode (sep=","), but loadtxt is the more capable reader for text.
Source: numpy.fromfile and numpy.frombuffer
Masked arrays
Neither .npy nor .npz can store a numpy.ma.MaskedArray. np.save raises NotImplementedError (from
MaskedArray.tofile) after the header has been written, which leaves a truncated .npy file. np.savez raises nothing
but drops the mask silently, so the file loads back as a plain array of the underlying data, masked values included.
Save the data and the mask as separate plain arrays and rebuild the masked array after loading:
import numpy.ma as ma
m = ma.masked_array([1.0, 2.0, 3.0], mask=[False, True, False])
try:
np.save("m.npy", m)
except NotImplementedError as e:
print("NotImplementedError:", e)
np.savez("m.npz", data=m.data, mask=ma.getmaskarray(m))
with np.load("m.npz") as f:
print(ma.masked_array(f["data"], mask=f["mask"]))
NotImplementedError: MaskedArray.tofile() not implemented yet. [1.0 -- 3.0]
Other options are m.filled(np.nan) for floating-point data when masked and NaN values need not be told apart, pickle
for files you will only read back yourself, and formats with their own missing-value support, such as NetCDF or a
pandas column with a nullable dtype. Masked arrays themselves are covered in
Masked Arrays.
Source: numpy.ma.MaskedArray.tofile and numpy.savez
Choosing a function
| Task | Function | Remarks |
|---|---|---|
One array, exact round trip |
|
|
Several arrays in one file |
|
|
Larger-than-memory array |
|
The OS pages the data in on demand. |
Numeric text matrix |
|
Fast, strict, no missing values. |
Text with missing values or names |
|
Slower; returns structured or masked arrays. |
Masked array |
|
|
Binary with a fixed layout |
|
No header; specify dtype and byte order. |
Mixed types, dates, quoting, large tables |
pandas |
See the pandas section and Data Sources & File Formats. |
Interchange with other languages |
Parquet, HDF5, NetCDF, Zarr, CSV |
|
Pitfalls
-
np.loadof a pickled file executes code: never enableallow_pickle=Truefor untrusted input, and do not share object arrays. -
savetxtwrites full precision with its defaultfmt="%.18e", which is accurate but unreadable; a short format such as"%.2f"is readable but lossy. -
loadtxtwith a header line that is not marked as a comment raises a conversion error: setskiprowsorcomments. -
genfromtxtandloadtxtwithencoding=Nonedepend on the system locale; passencoding="utf-8". -
Raw files have no header: a wrong
dtypeor byte order produces garbage without any error, so checkarr.sizeagainst the expected shape. -
An
NpzFilekeeps the file open until closed: use awithblock.