将文件中的所有值截断为 Python 中小数点后的 6 位
Truncating all values in a file to 6 digits after the decimal in Python
我有一个文件,其中有数千个以科学计数法表示的值,小数点后最多 12 位。我正在尝试使用 Python 将此文件中的所有值截断为小数点后 6 位数字并覆盖现有文件。我可以只使用 decimal 包来做这个吗?
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")
我找到了您问题的答案:
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 个数字)并覆盖文件。
我有一个文件,其中有数千个以科学计数法表示的值,小数点后最多 12 位。我正在尝试使用 Python 将此文件中的所有值截断为小数点后 6 位数字并覆盖现有文件。我可以只使用 decimal 包来做这个吗?
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")
我找到了您问题的答案:
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 个数字)并覆盖文件。