Issue
Following is the code I am using to generate a list and write it to a text file:
import numpy as np
c = 0
a = []
for i in range(1, 16,1):
b = i/10
c += 1
a.append([c,b])
np.savetxt('test.txt', a, delimiter=" ", fmt="%s")
When the list a
is printed, the values taken by c
are integers. However, when the list a
is written to a file, c
becomes float. Is it possible to append float and also integer to a text file using numpy.savetxt
?
Solution
You can specify the format of each value. In your case where np.array(a)
produce a 2D array with 2 columns:
np.savetxt('your_file.txt',a,delimiter=' ',fmt='%d %f')
Where fmt = '%d %f'
correspond to an integer followed by a float.
The .txt
file now contains:
1 0.100000
2 0.200000
3 0.300000
4 0.400000
5 0.500000
6 0.600000
7 0.700000
8 0.800000
9 0.900000
10 1.000000
11 1.100000
12 1.200000
13 1.300000
14 1.400000
15 1.500000
Answered By - obchardon
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.