Hello!
I have file named DATA.TXT which contains:
Output:
colA,colB
324,234
346,341
147,346
234,567
368,405
344,643
235,235
236,567
I am trying to read this in using line-by-line (for learning purpose), then add new column with sum on first two number. So that when I save the new file, I get:
Output:
colA,colB,Sum
324,234,558
346,341,687
147,346,493
234,567,801
368,405,773
344,643,987
235,235,470
236,567,803
And so far I am using this code:
f = open('DATA.TXT', 'r')
next(f)
for line in f:
print(line),
f.close()
To take a little further,and is better to use
with open()
then don't need to use
close()
as it dos automatically.
with open('col.txt') as f:
next(f)
for line in f:
line = line.strip()
num1, num2 = line.split(',')
num1, num2 = int(num1), int(num2)
So now is ready to continue further,if i do a test after running this code.
>>> num1 + num2
803
As expected i get the last calculation.
Thank you! Tried Your solution and it works.
Added lines:
num3 = num1 + num2
print(num1,num2,num3)
Which gives the first row:
Output:
324,234,803
Now somehow have to append (?) it and use FOR cycle to loop every row or do "next i" like in Excel VBA.
I guess I solved my problem.
Here is the script:
with open('file.txt',"r") as in_file, open('file2.txt',"w") as out_file:
next(in_file)
for line in in_file:
line = line.strip()
num1, num2 = line.split(',')
num1, num2 = int(num1), int(num2)
num3 = num1 + num2
out_file.write(str(num1) + "," + str(num2) + "," + str(num3) + "\n")
continue
Which outputs external file "file2.txt", although without headers that I removed using command "next(in_file)"
Output:
324,234,558
346,341,687
147,346,493
234,567,801
368,405,773
344,643,987
235,235,470
236,567,803
Yes can do it like this.
Here an other version you can look at using
f-string
.
Also put in header line just as a example.
See that with string formatting(f-string) it look better no need for
str()
or
+
.
with open('col.txt') as f,open('total.txt', 'w') as f_out:
header = next(f)
c1, c2 = header.strip().split(',')
f_out.write(f'{c1} {c2} Sum\n')
for line in f:
line = line.strip()
num1, num2 = line.split(',')
num1, num2 = int(num1), int(num2)
num3 = num1 + num2
f_out.write(f'{num1} + {num2} ${num3}\n')
Output:
colA colB Sum
324 + 234 $558
346 + 341 $687
147 + 346 $493
234 + 567 $801
368 + 405 $773
344 + 643 $987
235 + 235 $470
236 + 567 $803
Thanks! Although a bit confusing is the header separating-adding thing.