Search code examples
pythontype-conversionscientific-notation

How to convert scientific notation value to float


I have txt files in the format:

 6.3894e+02 1.7316e+02 6.6733e+02 1.9942e+02 9.8697e-01
 6.4355e+02 1.7514e+02 6.8835e+02 2.0528e+02 9.7908e-01

I want to convert all these values into float as in:

 638.94 173.16 667.33 199.42 98.697
 643.55 175.14 688.35 205.28 97.908

My code is:

   import os
   for i in os.listdir():
       if i.endswith(".txt"):
          with open(i, "r+") as f:
               content = f.readlines()
               for line in content:
                   f.write(float(line))

Solution

  • You can't update a file in place like that. You can use the fileinput module for that.

    You need to split the line at whitespace, parse each of the numbers as floats, then write them the way you want.

    You can also use glob() to match all the .txt files instead of using os.listdir() and .endswith(). And since fileinput allows you to give it a list of files, you don't need the for loop.

    import fileinput
    from glob import glob
    
    
    with fileinput.input(files=glob("*.txt"), inplace=True) as f:
        for line in f:
            nums = map(float, line.split())
            print(*nums)