473,588 Members | 2,474 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

ValueError: need more than 3 values to unpack

Hello All,

I have a tab separated input file (data.txt) in text format - the file
looks like this

SCHOOL DEPART1 DEPART2 DEPART3
Harvard Economics Mathematics Physics
Stanford Mathematics Physics
Berkeley Physics
U.C.L.A Biology Genetics

I have to utilize Python and to generate four files based on my input
file. The files would have this structure:

First File
=============== =============== =====
Filename: Harvard.txt
Harvard
Economics
Mathematics
Physics =============== =============== =====

Second File
=============== =============== =====
Filename: Stanford.txt
Stanford
Mathematics
Physics

=============== =============== =====

The same pattern would follow for files 3 and 4.
I came up with this code,

=============== =============== ============
#! python # -*- coding: cp1252 -*-

InputFILENAME = "data.txt" #Name of the data fule containg all records
OutputFileExten sion = ".txt" #File extension of output files

for line in open(InputFILEN AME):

SCHOOL, DEPART1, DEPART2, DEPART3 = line.split('\t' )
f = open(SCHOOL.str ip() + OutputFileExten sion, "w+")

f.write("" +SCHOOL.strip() +"\n")
f.write(">> " +DEPART1.strip( ) +"\n")
f.write(">> " +DEPART2.strip( ) +"\n")
f.write(">> " +DEPART3.strip( ) +"\n")
f.close() #InputFILENAME

# end
=============== =============== ============
I am having problems as the program will not work if all three DEPART
values are not present. If I populate all DEPART values for all records
program functions without issues.

When I run the check module, I get the following:
Traceback (most recent call last):
File "D:\Documen ts and
Settings\admini strator\Desktop \code\test\test code.py", line 8, in ?

SCHOOL, DEPART1, DEPART2, DEPART3 = line.split('\t' )
ValueError: need more than 3 values to unpack


How do I solve this problem and change the program so it does not stop
if a data record has less than three DEPART values.

Thanks for your help!

Elezar

Jan 21 '06 #1
3 24793

Elezar Simeon Papo wrote:
Hello All,

I have a tab separated input file (data.txt) in text format - the file
looks like this

SCHOOL DEPART1 DEPART2 DEPART3
Harvard Economics Mathematics Physics
Stanford Mathematics Physics
Berkeley Physics
U.C.L.A Biology Genetics

I have to utilize Python and to generate four files based on my input
file. The files would have this structure:

First File
=============== =============== =====
Filename: Harvard.txt
Harvard
Economics
Mathematics
Physics =============== =============== =====

Second File
=============== =============== =====
Filename: Stanford.txt
Stanford Mathematics
Physics =============== =============== =====

The same pattern would follow for files 3 and 4.
I came up with this code,

=============== =============== ============
#! python # -*- coding: cp1252 -*-

InputFILENAME = "data.txt" #Name of the data fule containg all records
OutputFileExten sion = ".txt" #File extension of output files

for line in open(InputFILEN AME):

SCHOOL, DEPART1, DEPART2, DEPART3 = line.split('\t' )
f = open(SCHOOL.str ip() + OutputFileExten sion, "w+")

f.write("" +SCHOOL.strip() +"\n")
f.write(">> " +DEPART1.strip( ) +"\n")
f.write(">> " +DEPART2.strip( ) +"\n")
f.write(">> " +DEPART3.strip( ) +"\n")
f.close() #InputFILENAME

# end
=============== =============== ============
I am having problems as the program will not work if all three DEPART
values are not present. If I populate all DEPART values for all records
program functions without issues.

When I run the check module, I get the following: Traceback (most recent call last):
File "D:\Documen ts and
Settings\admini strator\Desktop \code\test\test code.py", line 8, in ?

SCHOOL, DEPART1, DEPART2, DEPART3 = line.split('\t' )
ValueError: need more than 3 values to unpack

How do I solve this problem and change the program so it does not stop
if a data record has less than three DEPART values.

Thanks for your help!


Sounds like homework ;-)

if you do :

values = line.split('\t' )

Then you have a list with all the separate values in it.
You can then do the first line :

f.write("" +values[0].strip() +"\n")

Then the rest...

for entry in values[1:]:
f.write(">> " +entry.strip() +"\n")

This will work whatever the number of values. It won't report any badly
formed lines to you though.

All the best,

Fuzzyman
http://www.voidspace.org.uk/python/index.shtml Elezar


Jan 21 '06 #2
"Elezar Simeon Papo" <el************ **@yahoo.com> wrote:
SCHOOL, DEPART1, DEPART2, DEPART3 = line.split('\t' )
ValueError: need more than 3 values to unpack

How do I solve this problem and change the program so it does not stop
if a data record has less than three DEPART values.


The problem is that when you unpack a sequence, you must have exactly the
same number of variables as you have values. The idiom I use in a
situation where I'm not sure how many values I've got in the sequence is:

words = line.split('\t' )+ 4 * [None]
firstFourWords = words[0:3]
SCHOOL, DEPART1, DEPART2, DEPART3 = firstFourWords

The first line generates a list of words which is guaranteed to have at
least 4 elements in it. The second line gets the first four of those
words, and the last line unpacks them (in real life, I'd probably have
combined the second and third lines, but I spread it out here for
educational purposes).

If line is "HardKnocks\tFo o", you'll end up unpacking ["HardKnocks ", "Foo",
None, None]. Depending on your application, you may want to pad with empty
strings instead of None.

It would be convenient if string.split() took an optional 'minsplit'
argument as well as a 'maxsplit'. Then you could have just done:

school, dept1, dept2, dept3 = line.split ('\t', 4, 4)

but, alas, it doesn't work that way.
Jan 21 '06 #3
Thanks a lot guys. this solved the problem.
Best
Elezar

----------------------------------------------------------
Izraz.com - an open bosnian-croatian-serbian dictionary
http://izraz.com/Category:Medicinska_stanja

Feb 7 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
1246
by: hikums | last post by:
How to get the header values in the sql with union. For example, select deptno as dep,deptname as dname,location as loc,mgrno as mgr from dept union select empno,empname,'Employee','' from emp I need output with header:
3
2201
by: Ron | last post by:
I need a way to read the hex values of an old DBase3 data file. Can anyone give me some info regarding how to grab hex values out of a file? Not sure exactly how to do this. Thanks for your help.
9
2108
by: JD | last post by:
Hi guys What if I need to return two values from a function. What's the best way to do it? Function is to load a text file into memory like so: -----8<----- char *LoadFile(char *infile)
2
1744
by: k.retheesh | last post by:
Hi, I am very new to pyton, during my adventures journey I got the following error message which am not able to solve, can somebody help me. I was trying to format my output in a readable way, Compare results in tblItem ________________________________________________________________________________ 71 records found in pctrsqlstage case9125 71 records found in qa-sql2\pctr case9126
2
2026
by: mumbaimacro | last post by:
hi i have two combo boxes in a form with values from a table. i need a report to be opened by a button from the form ,The Report should show the values selected in the combo boxes in the form and also i am going to show some other values from tables in the report with that. example: form view: month: jan --> selected from combobox year : 2006 --> selected from combobox
0
6847
by: laxmikiran.bachu | last post by:
ValueError: need more than 1 value to unpack . This is the error I get when I am using pyRXPU in the one of the scripts to get the strings from an application. Can anybody throw some light on this ..what might be the solution for this. If I use pyRXP iam not getting the mentioned error. Error information for the reference :
8
7110
by: Shawn Minisall | last post by:
I am trying to read a few lines of a file with multiple values, the rest are single and are reading in fine. With the multiple value lines, python says this "ValueError: too many values to unpack" I've googled it and it says that happens when you have too few or too many strings that don't match with the variables in number your trying to assign them too. Below are the lines in reading in:
4
9386
by: f0rd | last post by:
Hi everybody, I have a python script I developed for work, that organises sound samples and out puts them to a text file. Here is an example input file:Sound001,15,6 Sound002,15,6 Sound003,30,3 Sound004,30,3 Sound005,30,3 Sound006,60,6 Sound007,60,6 Sound008,60,6
0
7929
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8228
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8357
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8223
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6634
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
5729
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5398
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3887
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1459
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.