In Python, we use the loadtxt()
function to load data from a text file, provided that each row in the file has the same number of features or values.
Why should we use this function when we've got the genfromtxt()
function to read files in a sophisticated manner, e.g., filling NA or missing values? The answer is simple. The loadtxt()
function provides native Numpy arrays implementation for faster file loading and reading.
loadtxt(fname,dtype=<class 'float'>,comments='#',delimiter=None,converters=None,skiprows=0,usecols=None,unpack=False,ndmin=0,encoding='bytes',max_rows=None,*,like=None)
It takes the following argument values. These argument values help to process data values efficiently.
Name | Description | Required/Optional |
| Generator or file name to read. If the input file is of | Required |
|
| Optional |
|
| Optional |
|
| Optional |
|
| Optional |
|
| Optional |
|
| Optional |
|
| Optional |
|
| Optional |
|
| Optional |
|
| Optional |
| Variable number of argument values. | Optional |
|
| Optional |
The loadtxt()
function returns data from the text file in the form of an ndarray
.
In the example below, we're going to explain the working of the loadtxt()
function in different scenarios. Let's have an in-depth coding explanation.
0 1 2 7 83 4 5 6 67 8 9 0 -1
open()
method to load the file.txt
file in the current program and return a file descriptor fd
.data.readlines()
to create a pipeline to fetch file.txt
attached to data
file descriptor. The readlines()
function will return an ndarray
with each line of the file as a list.loadtxt(lines)
to load data with same format.np.loadtxt()
to load file data according to the provided dtype
format.fd
associated to file.txt
.