← Back to NumPy Course | Chapter 11: File I/O | Lesson 2 of 5

np.savetxt/loadtxt

savetxt writes plain-text files you can open anywhere and loadtxt reads them back.

In this page:

  1. np.savetxt/loadtxt
Syntax
python
np.savetxt("file.txt", arr, delimiter=",")
arr = np.loadtxt("file.txt", delimiter=",")

np.savetxt/loadtxt

np.savetxt writes an array as delimited text and np.loadtxt reads it into an array. Use delimiter="," for CSV-like files and fmt to control number formatting. Text files are portable but larger and lose exact dtype information.

Note: header and comments arguments let you add and skip a title line.

Example: np.savetxt/loadtxt

python
import numpy as np
import io

a = np.array([[1.5, 2.5], [3.5, 4.5]])
buf = io.StringIO()
np.savetxt(buf, a, delimiter=",", fmt="%.1f")
text = buf.getvalue()
print(text)
back = np.loadtxt(io.StringIO(text), delimiter=",")
print(back)

# Output:
# 1.5,2.5
# 3.5,4.5
#
# [[1.5 2.5]
#  [3.5 4.5]]
Related Topics
Common Mistakes
  1. Forgetting the delimiter when reading
  2. Losing precision with a short fmt
  3. Trying to load text with missing values using loadtxt
Chapter Summary
  • savetxt writes text
  • loadtxt reads text
  • delimiter sets the separator
  • fmt controls formatting
🔒

Chapter Quiz — Complete all 5 topics to unlock

0/5 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.