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 > OutputFileExtension = ".txt" #File extension of output files > > for line in open(InputFILENAME): > > SCHOOL, DEPART1, DEPART2, DEPART3 = line.split('\t') > f = open(SCHOOL.strip() + OutputFileExtension, "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:\Documents and > Settings\administrator\Desktop\code\test\testcode.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 -- http://mail.python.org/mailman/listinfo/python-list