Reputation:
I have a text file like this example:
fit c3 start=1455035 step=1
2.000000
2.000000
2.000000
2.000000
2.000000
2.000000
fit c2 start=5195348 step=1
1.000000
1.000000
1.000000
1.000000
1.000000
fit c4 start=6587009 step=1
10.000000
10.000000
10.000000
10.000000
10.000000
each text line(starting with fit) is followed by some number lines. I want to sum all numbers which are below each text line (so they are in the same group) and replace the last number of that group by the sum of number of that specific group and also replace the rest of numbers by 1.000000 - like in this output example:
fit c3 start=1455035 step=1
1.000000
1.000000
1.000000
1.000000
1.000000
12.000000
fit c2 start=5195348 step=1
1.000000
1.000000
1.000000
1.000000
5.000000
fit c4 start=6587009 step=1
1.000000
1.000000
1.000000
1.000000
50.000000
and write it into a new file.
I tried this code in Python, but actually did not return what I want.
infile = open("file.txt", "r")
for line in infile:
if line startswith"fit":
for l in len(line):
line[l] = line + line[l+1]
Do you know how to do that in python?
Upvotes: 0
Views: 57
Reputation: 734
Please, try this out.
prev_string = ' '
global_string = ''
temp_sum = 0
with open('file.txt', 'r') as f:
prev_string = f.readline()
for line in f:
if prev_string[0] == 'f':
global_string += prev_string
elif (line[0].isdigit() and prev_string[0].isdigit()):
global_string += '1.000000\n'
temp_sum += float(prev_string[:-1])
else:
temp_sum += float(prev_string[:-1])
global_string += str(format(temp_sum, '.6f')) + '\n'
temp_sum = 0
prev_string = line
global_string += str(format(temp_sum + float(prev_string[:-1]), '.6f'))
with open('output.txt', 'w') as out:
out.write(global_string)
Upvotes: 0
Reputation: 14096
lines = open("file.txt", "r").read().splitlines()
_sum = 0.
for i, line in enumerate(lines):
if not line.startswith('fit') :
_sum += float(line)
lines[i] = '{:0.6f}'.format(1.)
if line.startswith('fit') and i > 0:
lines[i-1] = '{:0.6f}'.format(_sum)
_sum = 0
elif i+1 >= len(lines):
lines[i] = '{:0.6f}'.format(_sum)
print '\n'.join(lines)
output
fit c3 start=1455035 step=1
1.000000
1.000000
1.000000
1.000000
1.000000
12.000000
fit c2 start=5195348 step=1
1.000000
1.000000
1.000000
1.000000
5.000000
fit c4 start=6587009 step=1
1.000000
1.000000
1.000000
1.000000
50.000000
Upvotes: 2