Append Float Data At The End Of Each Line In A Text File
I have a .txt file and I'm trying to add float number at the end of each line with incremented value than the last line. This is what I have in the .txt file: >520.980000 172.90
Solution 1:
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')
defget_number(_):
global counter
counter += Decimal('0.1')
return" "+str(counter)+'\n'withopen("input.txt","r") as f:
data = f.read()
out = re.sub('\n',get_number,data)
withopen("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.
Solution 2:
Without other modules (not that you should avoid them!):
withopen("numbers.txt", "rt") as fin:
withopen("numbers_out.txt", "wt") as fout:
counter = 1.0for line in fin:
counter += 0.1
fout.write(f"{line.rstrip()}{counter:.1f}\n")
numbers_out.txt:
>520.980000 172.900000 357.440000 1.1>320.980000 192.900000 357.441000 1.2>325.980000 172.900000 87.440000 1.3
Post a Comment for "Append Float Data At The End Of Each Line In A Text File"