Python reads floating point Numbers and reads text file examples
- 2020-04-02 13:38:36
- OfStack
Reading floating point data from a text file is one of the most common tasks. Python doesn't have an input function like scanf, but we can use regular expressions to extract floating point Numbers from the read string
import re
fp = open('c:/1.txt', 'r')
s = fp.readline()
print(s)
aList = re.findall('([-+]?d+(.d*)?|.d+)([eE][-+]?d+)?',s) # Searches for strings using regular expressions
print(aList)
for ss in aList:
print(ss[0]+ss[2])
aNum = float((ss[0]+ss[2]))
print(aNum)
fp.close()
File contents:
12.540 56.00 1.2e2 -1.2E2 3.0e-2 4e+3
Output results:
12.540 56.00 1.2e2 -1.2E2 3.0e-2 4e+3
[('12.540', '.540', ''), ('56.00', '.00', ''), ('1.2', '.2', 'e2'), ('-1.2', '.2', 'E2'), ('3.0', '.0', 'e-2'), ('4', '', 'e+3')]
12.540
12.54
56.00
56.0
1.2e2
120.0
-1.2E2
-120.0
3.0e-2
0.03
4e+3
4000.0
Comments:
Read into a text file by line, use regular expressions to find floating points in strings, and use the float() function to convert strings to floating points