numpy.loadtxt() reads simple text data into a NumPy array. It is best for regular files where each row has the same number of columns and missing values are not expected.
The official NumPy documentation covers numpy.loadtxt(), numpy.genfromtxt(), and numpy.savetxt(). Related PythonPool guides cover NumPy asarray, NumPy axis, and NumPy reshape.
Use loadtxt() for clean numeric text files, small CSV-like files, and quick imports from whitespace-separated or single-character-delimited data. If the file has missing fields or irregular rows, genfromtxt() is usually a better fit.
Current NumPy supports options such as dtype, delimiter, skiprows, usecols, converters, ndmin, encoding, and quotechar. In recent NumPy versions, delimiters must be a single character, and the default encoding is None.
Most examples below use io.StringIO so the code is self-contained. In real code, pass a file path, file object, or generator that yields lines.
Be explicit about delimiters and dtypes when reading files produced by another tool. That makes the import easier to review and avoids surprises when whitespace, commas, or quoted fields are present.
The main limitation is regularity. loadtxt() expects each row that is read to have a compatible number of columns. It is not designed to repair missing cells, mixed row lengths, or complex spreadsheet-style files.
Comments are skipped by default when a line begins with the comment marker. If your source file uses metadata rows, comments, or headers, decide whether skiprows, comments, or another parser best matches the file structure.
For text encodings, current NumPy defaults to normal system text decoding behavior through encoding=None. When you know the file encoding, setting it explicitly can make scripts more portable.
Read Whitespace Separated Numbers
By default, loadtxt() reads whitespace-separated numeric data.
import numpy as np
from io import StringIO
text = StringIO("""1 2 3
4 5 6
7 8 9""")
data = np.loadtxt(text)
print(data)
The result is a floating-point array.
Each text row becomes one row in the array.
This is the simplest form when the input has clean numeric columns.
If one row has fewer or more values than the others, this simple import will fail. That failure is helpful because it signals that the input is not a regular numeric table.
Read Comma Separated Values
Pass a delimiter for CSV-like text.
import numpy as np
from io import StringIO
text = StringIO("""1,2,3
4,5,6""")
data = np.loadtxt(text, delimiter=",")
print(data)
The delimiter must be a single character in current NumPy.
For full CSV parsing with complex quoting rules, the Python csv module or pandas may be more appropriate.
For simple numeric comma-delimited files, loadtxt() is often enough.
Quoted fields can be handled with quotechar for straightforward cases. For complicated CSV files with embedded delimiters, escaped quotes, or mixed text and numbers, use a CSV-aware parser.
Choose A dtype
Use dtype when the file should load as a specific numeric type.
import numpy as np
from io import StringIO
text = StringIO("""1 2
3 4""")
data = np.loadtxt(text, dtype=int)
print(data)
print(data.dtype)
This reads the values as integers.
If the text contains decimals and dtype=int is used, NumPy will raise an error instead of silently rounding.
Choose the dtype that matches the data format.
When you are not sure, load a small sample first and inspect both the values and the dtype before processing the entire file.
Skip Header Rows
Use skiprows to ignore header or metadata rows.
import numpy as np
from io import StringIO
text = StringIO("""speed,distance
10,100
20,240""")
data = np.loadtxt(text, delimiter=",", skiprows=1)
print(data)
The first row is skipped before parsing numeric values.
This is useful for simple files with one header line.
If the header is complex or mixed with comments, inspect the file before relying on a fixed row count.
For files with named columns, loadtxt() will not create a labeled table by itself. It returns an array, so column meaning needs to come from your code or separate metadata.
Select Columns With usecols
usecols reads only selected columns.
import numpy as np
from io import StringIO
text = StringIO("""1,10,100
2,20,200
3,30,300""")
data = np.loadtxt(text, delimiter=",", usecols=(0, 2))
print(data)
This keeps the first and third columns.
Column indexes are zero-based.
Use this when a file contains extra columns that are not needed for the calculation.
Reading only needed columns can also reduce memory use for wide text files, especially when the file contains many unused numeric fields.
Use A Converter Function
Converters transform text fields before NumPy stores them.
import numpy as np
from io import StringIO
text = StringIO("""1,10%
2,25%""")
def percent_to_float(value):
return float(value.rstrip("%")) / 100
data = np.loadtxt(text, delimiter=",", converters={1: percent_to_float})
print(data)
This converter removes the percent sign and converts the value to a decimal fraction.
Converters are helpful for small, predictable transformations.
For messy files, missing values, or mixed data types, switch to genfromtxt() or a dedicated data-loading tool.
Converters should stay small and predictable. If a converter needs complicated branching, it is usually a sign that the file should be cleaned before loading or parsed with a more flexible tool.
In short, use np.loadtxt() for regular text data, set the delimiter and dtype deliberately, use skiprows and usecols for simple file structure, and choose genfromtxt() when the input is irregular.