Error: too many values to unpack - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Error: too many values to unpack (/thread-22117.html) |
Error: too many values to unpack - Mike - Oct-30-2019 Hello, I have a script that should open external ascii file, take the first two columns, add each row and output file with first two columns with sum as a third column. I have a quite big (1.6 Mb) data ascii files so I get an error: 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')Data - ascii file: Quote:Header1 Header2 Header3 Header4 Header5 Header6 Header7 Header8 Header9 Header10 Output that I would like to see:Quote:Header1 Header2 Sum RE: Error: too many values to unpack - buran - Oct-30-2019 one way is to add catch all variable 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 |