Python Forum
Error: too many values to unpack
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Error: too many values to unpack
#2
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
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

Reply


Messages In This Thread
Error: too many values to unpack - by Mike - Oct-30-2019, 02:57 PM
RE: Error: too many values to unpack - by buran - Oct-30-2019, 03:07 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Too much values to unpack actualpy 3 518 Feb-11-2024, 05:38 PM
Last Post: deanhystad
  Trying to use 2 values from excel in my script but getting error.. cubangt 3 1,722 May-11-2022, 07:12 AM
Last Post: normanwolf
  unpack dict menator01 1 1,241 Apr-09-2022, 03:10 PM
Last Post: menator01
  ValueError: not enough values to unpack (expected 4, got 1) vlearner 2 6,395 Jan-28-2022, 06:36 PM
Last Post: deanhystad
  [SOLVED] [geopy] "ValueError: too many values to unpack (expected 2)" Winfried 2 2,913 Mar-30-2021, 07:01 PM
Last Post: Winfried
  Cannot unpack non-iterable NoneType object, i would like to ask for help on this. Jadiac 3 8,993 Oct-18-2020, 02:11 PM
Last Post: Jadiac
  Argparse error when inputting values tqader 2 2,936 Sep-11-2020, 07:42 PM
Last Post: buran
  subprogram issues: cannot unpack non-iterable function object error djwilson0495 13 6,094 Aug-20-2020, 05:53 PM
Last Post: deanhystad
  struct.unpack failed Roro 2 3,400 Jun-13-2020, 05:28 PM
Last Post: DreamingInsanity
  Can't unpack values of dictionary with ** Snake 3 3,631 Mar-11-2020, 11:17 AM
Last Post: Snake

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020