【问题标题】:Truncating all values in a file to 6 digits after the decimal in Python在Python中将文件中的所有值截断为小数点后6位
【发布时间】:2023-10-27 04:09:01
【问题描述】:

我有一个文件,其中包含数千个科学计数法值,小数点后最多 12 位。我正在尝试使用 Python 将此文件中的所有值截断为小数点后 6 位并覆盖现有文件。我可以只使用十进制包吗?

 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")

 

【问题讨论】:

标签: python truncate


【解决方案1】:

我找到了您问题的答案:

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

这成功地将文件的每个数字截断到小数点后 6 位(每行应该有 1 个数字)并覆盖文件。

【讨论】:

  • 谢谢,这正是我要找的
最近更新 更多