Numpy loadtxt – Python NumPy loadtxt() Function

NumPy loadtxt() Function:

Numpy loadtxt: To load data from a text file, use the loadtxt() function of the NumPy module. In a text file, each row of the text file must have the same number of values.

Syntax:

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

Parameters

filename: This is required. The file, filename, or generator to read is specified by this argument. If the filename extension is.gz or.bz2, we’ll start by decompressing the file. After that, the generators will return Python 3k byte strings. It’s important to note that generators should only return byte strings.

dtype: This is optional. The datatype of the output array is indicated by this argument. float is the default value.

Return value

np loadtext: The data read from the text file is returned.

NumPy loadtxt() Function in Python

Example1

Approach:

  • Import numpy module using the import keyword
  • Pass some random list as an argument to the array() function
    of the Numpy module to create an array.
  • Store it in a variable.
  • Save the above-given array as a text file with some random filename using the savetxt() function of the Numpy module
  • Load the above textfile using the loadtxt() function of the Numpy module
  • Print the above file content.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
# Pass some random list as an argument to the array() function
# of the Numpy module to create an array. 
# Store it in a variable.
gvn_arry = np.array([1, 12, 35, 20, 70])                     

# Save the above given array  as a text file with some random filename
# using the savetxt() function of the Numpy module
np.savetxt("samplefile", gvn_arry)

# Load the above textfile using the loadtxt() function of the Numpy module
file_content = np.loadtxt("samplefile")
print()
# Print the above file content
print("The above file content:")
print(file_content)

Output:

The above file content:
[ 1. 12. 35. 20. 70.]