np.savetxt/loadtxt
savetxt writes plain-text files you can open anywhere and loadtxt reads them back.
In this page:
Syntax
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
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
- Forgetting the delimiter when reading
- Losing precision with a short fmt
- 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: