-1

I have a file that has thousands of values in scientific notation up to 12 digits after the decimal. I am trying to use Python to truncate all values in this file to 6 digits after the decimal and overwrite the existing file. Can I just use the decimal package to do this?

 from decimal import Decimal as D, ROUND_DOWN

 with open("foo.txt", "a") as f:
    f.D('*').quantize(D('0.000001'), rounding=ROUND_DOWN)
    f.write("foo.txt")

 

Kevin
  • 75
  • 3

1 Answers1

1

I found an answer to your question:

with open("foo.txt", "r+") as f:
    # getting all the lines before erasing everything
    lines = f.readlines()
    #setup for the erasion (idk why it's necessary but it doesn't work without this line)
    f.seek(0)
    f.truncate(0) # erasing the content of the file

    for line in lines:
        f.write(f'{float(line):.6f}\n') # truncating the value and appending it to the end of the file

This succesfully truncate every number of the file up to 6 decimals (there should be 1 number by line) and overwrites the file.

S-c-r-a-t-c-h-y
  • 321
  • 2
  • 5