[Solved] Append float data at the end of each line in a text file


I would do it following way:
Assume that you have file input.txt:

520.980000 172.900000 357.440000
320.980000 192.900000 357.441000
325.980000 172.900000 87.440000

then:

from decimal import Decimal
import re
counter = Decimal('1.0')

def get_number(_):
    global counter
    counter += Decimal('0.1')
    return " "+str(counter)+'\n'

with open("input.txt","r") as f:
    data = f.read()

out = re.sub('\n',get_number,data)

with open("output.txt","w") as f:
    f.write(out)

After that output.txt is:

520.980000 172.900000 357.440000 1.1
320.980000 192.900000 357.441000 1.2
325.980000 172.900000 87.440000 1.3

Note that I used Decimal to prevent problems with float (like something.999999…) appearing. I used regular expression (re) to find newlines (\n) and replace it with subsequent numbers by passing function as 2nd re.sub argument.

6

solved Append float data at the end of each line in a text file