Python Forum
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
355.76389 -4.2 -5.1 -4.4 -3.9 -3 -3.5 -2.8 -2.4 -4.1
355.7847233 -6 -3.7 -4.6 -2.8 -2.5 -3.6 -5.9 -3 0.6
355.8055567 -4.5 -6.8 -6.3 -3.8 -4.3 -5.2 -5.1 -4.3 -3.6
355.82639 -4.2 -4.7 -6.5 -3.9 -4.1 -4.7 -2.7 -5.3 -4.1
355.8472233 -6.6 -4.4 -4.4 -4.7 -2 -4.6 -4 -4.5 -4.8
355.8680567 -3.5 -2.2 -2.7 -4.1 -4.6 -6 -5.7 -3 -1.9
...

Error:
c1, c2 = header.strip().split(' ') ValueError: too many values to unpack (expected 2)
Output that I would like to see:
Quote:Header1 Header2 Sum
355.76389 -4.2 351.56389
355.7847233 -6 349.7847233
355.8055567 -4.5 351.3055567
355.82639 -4.2 351.62639
355.8472233 -6.6 349.2472233
355.8680567 -3.5 352.3680567
...



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 want

another way is to use slicing when unpacking
c1, c2 = header.strip().split(' ')[:2]
Then same for num1 and num2 unpacking

another 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