Python:如何以特定格式在文件中写入数据?

时间:2010-05-04 08:19:34

标签: python string-formatting

我有一个名为MAC1_Val的数组:

  
    
      

MAC1_Val       数组([1.00000000e + 00,-1.00000000e + 01,-2.06306600e + 02,                2.22635749e + 02,1.0000000000e + 00,1.0000000000e + 01,                1.00000000e + 01,-2.06306600e + 02,2.22635749e + 02,                0.00000000e + 00,0.00000000e + 00,0.00000000e + 00,                0.00000000e + 00,0.00000000e + 00,0.00000000e + 00,                0.00000000e + 00,0.00000000e + 00,0.00000000e + 00,                0.00000000e + 00,0.00000000e + 00,0.00000000e + 00,                0.00000000e + 00,0.00000000e + 00,0.00000000e + 00,                0.00000000e + 00,0.00000000e + 00,1.0000000000e + 00,               -1.08892735e + 01,1.88607749e + 01,1.03153300e + 01,               -1.78666757e + 01,3.333333333e-07,-3.33333333e-07,               -4.21637021e-05,4.21637021e-05,9.98844400e-01,               -1.73973001e-03,1.20938900e-03,1.87742948e-03,               -3.33333333e-03,6.66666667e-03,-3.33333333e-03,               -2.64911064e-01,-2.60959501e + 01,2.81614422e + 01,                3.33333333e-03,-6.66666667e-03,3.333333333e-03,                0.00000000e + 00,0.00000000e + 00])

    
  

我希望以特定格式写入文件(.txt)值,如下所示:

1.000000e+00
-1.000000e+01 
-2.063066e+02
2.226357e+02
1.000000e+00   
1.000000e+01 .......

请注意,浮点数后面有6位数

有任何建议如何做到这一点? 提前谢谢!

2 个答案:

答案 0 :(得分:2)

printf 标准是你的朋友:

for i in MAC1_Val:
    print "%.6e" % i

1.000000e+00
-1.000000e+01
-2.063066e+02
2.226357e+02
1.000000e+00
1.000000e+01
1.000000e+01

答案 1 :(得分:1)

使用string interpolation格式化数字。

'%.3f' % (1.23456,)