Imagine you have a textfile input.txt
containing text and floats, but without a regular structure (such as header, .csv etc.), for instance :
Banana 1.4030391
(4.245, -345.2456)
4.245 -345.2456
Hello how are you?
Based on this file, you want to generate output.txt
where each float has been rounded to 1 decimal, the remaining content left untouched. This would give
Banana 1.4
(4.2, -345.2)
4.2 -345.2
Hello how are you?
To achieve this in Python, you need following steps.
- Open the inputfile and read each line
f = open('input.txt') f.readlines()
- Extract the floats
How to proceed? The difficulty lies in the fact that there is no regular structure in the file.
- Round the floats
np.round(myfloat)
- Write the line to the output file
...