SoFunction
Updated on 2024-10-30

Example of python using numpy to read, save txt data

1. First generate an array

import numpy as np
a = (5,5)
print(a)

Results:

array([[0.17374613, 0.87715267, 0.93111376, 0.53415215, 0.59667207],
 [0.6865835 , 0.15873242, 0.2842251 , 0.73840834, 0.37163279],
 [0.06556834, 0.68446787, 0.91136611, 0.82796704, 0.81343561],
 [0.99336674, 0.22961447, 0.78337783, 0.12448455, 0.04388831],
 [0.50053951, 0.046609 , 0.98179001, 0.446681 , 0.68448799]])

2. Save to txt

Using functions, the documentation is here:

/doc/numpy-1.14.2/reference/generated/#

('',a,fmt='%0.8f')
# The first parameter is the name of the file to be saved
# The second argument is the array to be saved
#The third parameter is the format of the saved data,See documentation for details

Results:

python numpy读取、保存txt

3. Read data from the txt file

b=('',dtype=np.float32)
print(b)

Results:

array([[0.17374612, 0.8771527 , 0.9311138 , 0.53415215, 0.59667206],
 [0.6865835 , 0.15873241, 0.2842251 , 0.7384083 , 0.37163278],
 [0.06556834, 0.68446785, 0.9113661 , 0.82796705, 0.8134356 ],
 [0.9933667 , 0.22961447, 0.7833778 , 0.12448455, 0.04388831],
 [0.5005395 , 0.046609 , 0.98179 , 0.446681 , 0.684488 ]],
 dtype=float32)

The above example of this python using numpy to read and save txt data is all that I have shared with you.