使用舍入值重写文本文件中的行的最佳方法

时间:2014-06-12 18:36:36

标签: python file text rounding

我有一个包含多行的文本文件。每行都有以空格分隔的值:

0.004061345 0.02444009 -0.02234149 -0.01368116 0.02479915 5.76696e-012 

我正在寻找重写相同文本文件的最佳方法,但其中包含舍入值:

0.004 0.024 -0.022 -0.014 0.025 0.000 

最恐怖的方式是什么?

Here is my solution, a combinaison of PepperoniPizza and Jan Vlcinsky

代码:

stringNewFile = ''
i = 0 #-- My file as a header that I need to keep untouch

with open('myfile.txt', 'rb') as fin:
for line in fin.readlines():
    stringNewFile = stringNewFile + line if i < 6 else stringNewFile + " ".join(map(lambda itm: "{0:.3f}".format(float(itm)), line.split()))+'\n'
    i = i + 1


file_handle = open('myfile.txt', 'w')
file_handle.write(stringNewFile)
file_handle.close()

干杯!

3 个答案:

答案 0 :(得分:1)

读取每一行,将行拆分为单独的字符串,将每个字符串转换为浮点数并将其舍入,然后写入新文件。

fout = open('rounded.txt', 'wb')

with open(input, 'rb') as fin:
    for line in fin.readlines():
        values = line.split()
        for val in values:
            new_val = round(float(val), 3) # 3 digit precision
            fout.write(new_val)
            fout.write(' ')
        fout.write('\n')

fout.close()

答案 1 :(得分:0)

如何使用带有空格的CSV库作为分隔符,如下所示:

import csv

def test():
    out_csv_file = open('output.csv', 'w')
    with open('test.csv', 'r') as in_csv_file:
        reader = csv.reader(in_csv_file, delimiter=' ')
        writer = csv.writer(out_csv_file, delimiter=' ')
        for row in reader:
            line_buffer = []
            for item in row:
                line_buffer.append(round(float(item), 3))
            writer.writerow(line_buffer)

答案 2 :(得分:0)

很快(重新格式化该行):

>>> textin = "0.004061345 0.02444009 -0.02234149 -0.01368116 0.02479915 5.76696e-012"
>>> " ".join(map(lambda itm: "{:5.3f}".format(float(itm)), textin.split()))
'0.004 0.024 -0.022 -0.014 0.025 0.000'

一步一步:

>>> textin = "0.004061345 0.02444009 -0.02234149 -0.01368116 0.02479915 5.76696e-012"
>>> textin.split()
['0.004061345',
 '0.02444009',
 '-0.02234149',
 '-0.01368116',
 '0.02479915',
 '5.76696e-012']
>>> num = 3.141516
>>> "{:5.3f}".format(num)
'3.142'
>>> map(lambda itm: "{:5.3f}".format(float(itm)), textin.split())
['0.004', '0.024', '-0.022', '-0.014', '0.025', '0.000']
>>> " ".join(map(lambda itm: "{:5.3f}".format(float(itm)), textin.split()))
'0.004 0.024 -0.022 -0.014 0.025 0.000'

申请文件转换:

infile = "input.txt"
outfile = "output.txt"
with open(infile) as f_in, open(outfile, "w") as f_out:
    for line in f_in:
        line = line.strip("\n") #remove trainilg newline, if present
        line = " ".join(map(lambda itm: "{:5.3f}".format(float(itm)), textin.split()))
        f_out.write(line + "\n")

注意:不要一次尝试读写同一个文件,这太难了。