NumPy Tutorial NumPy Statistics NumPy References

NumPy - loadtxt() function



The NumPy loadtxt() function is used to load data from a text file. Each row in the text file must have the same number of values.

Syntax

numpy.loadtxt(fname, dtype=<class 'float'>)

Parameters

fname Required. Specify File, filename, or generator to read. If the filename extension is .gz or .bz2, the file is first decompressed. Note that generators should return byte strings.
dtype Optional. Specify data-type of the resulting array. Default: float.

Return Value

Returns the data read from the text file.

Example:

In the example below, array arr is saved into a text file called test.out. Further, the loadtxt() function is used to load the saved array from the file and print it.

import numpy as np

arr = np.array([10, 20, 30, 40, 50, 60])

#saving arr in text file - test.out
np.savetxt("test.out", arr)

#loading array from test.out
y = np.loadtxt("test.out")

#displaying the content of y
print(y)

The output of the above code will be:

[10. 20. 30. 40. 50. 60.]

Example:

The example below describes how to save multiple numpy arrays in a file and load the saved arrays from it. Please note that, each array must have same number of elements.

import numpy as np

x = y = z = np.arange(0.0,5.0,1.0)
np.savetxt("demo.txt", (x, y, z))

#loading array from demo.txt
NewArr = np.loadtxt("demo.txt")

#displaying the result
print(NewArr)

The output of the above code will be:

[[0. 1. 2. 3. 4.]
 [0. 1. 2. 3. 4.]
 [0. 1. 2. 3. 4.]]

❮ NumPy - Functions