one way is to add catch all variable
another way is to use slicing when unpacking
another way to process altogether the file is to use
Note that your example input file has no commas, although you split your line at commas. csv module will not work if the header and the data rows have different separator
with open('input.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')
*_
will catch all remaining values being unpacked. underscore is a valid variable name used to denote its a throw away variable, but you can use any name you wantanother way is to use slicing when unpacking
c1, c2 = header.strip().split(' ')[:2]Then same for
num1
and num2
unpackinganother way to process altogether the file is to use
csv
module and csv.DictReader
and csv.DictWriter
which will simplify the code.Note that your example input file has no commas, although you split your line at commas. csv module will not work if the header and the data rows have different separator
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs