python Method to read an txt file as np.array
- 2021-01-14 06:05:28
- OfStack
The original file:
7.8094,1.0804,5.7632,0.012269,0.008994,-0.003469,-0.79279,-0.064686,0.11635,0.68827,5.7169,7.9329,0.010264,0.003557,-0.011691,-0.57559,-0.56121,
The original file has a large number of data, which is 125 lines and 45 float numbers.
Code:
# -*- coding: utf-8 -*-
import numpy as np
def readFile(path):
# Open the file (note the path)
f = open(path)
# Line by line
first_ele = True
for data in f.readlines():
## Remove the newline character from each line, "\n"
data = data.strip('\n')
## In accordance with the Spaces are separated.
nums = data.split(',')
## Added to the matrix In the.
if first_ele:
### To join the matrix In the .
matrix = np.array(nums)
first_ele = False
else:
matrix = np.c_[matrix,nums]
matrix = matrix.transpose()
a = []
for x in range(0,125):
result = [float(item) for item in matrix[x]]
a.append(result)
arr=np.array(a)
f.close()
print(arr)
return arr
# test.
if __name__ == '__main__':
readFile(" ~ /s01.txt")
Output:
[[ 8.1305 1.0349 5.4217 ..., 0.74017 0.30053 -0.05773 ]
[ 8.1305 1.0202 5.3843 ..., 0.73937 0.30183 -0.057514]
[ 8.1604 1.0201 5.3622 ..., 0.73955 0.30052 -0.057219]
...,
[ 7.9517 1.1466 5.6081 ..., 0.73945 0.30342 -0.056789]
[ 7.9743 1.1542 5.5038 ..., 0.7403 0.30027 -0.056704]
[ 7.9812 1.0945 5.6005 ..., 0.73897 0.30275 -0.056262]]
Process finished with exit code 0