2021-03-30

np.loadtxt from string

np.loadtxt doesn't support loading from a nice old-fashioned str. Luckily, io.StringIO neatly solves this problem:

import io
import numpy as np

raw = """
# temperature, kappa, std
300,7.00000,1.03175
400,5.44444,0.76190
"""

with io.StringIO(raw) as f:
    data = np.loadtxt(f, delimiter=",")

Being able to pretend strings are files is surprisingly useful, especially for testing file-based import/export routines!