[Tutor] a quick Q: how to use for loop to read a series of files with .doc end

Alan Gauld alan.gauld at btinternet.com
Fri Oct 7 17:00:42 CEST 2011


On 07/10/11 11:25, Dave Angel wrote:

>>> for a,b in zip(results['E'],results['B']):
>>> summary.append(a+b)
>>
>> I don't know why this gives a key error on 'E' (which basically means
>> that there is no key 'E') since the code above should guarantee that
>> it exists. Odd. I'm also not sure why the error occurs after it prints
>> summary. Are you sure the output is in the sequence you showed in your
>> message?
>>
> One simple explanation: it continued on to the next file, which has
> neither "E" nor "B" in it.

But even then this bit of code should ensure that a list of zeros exists:

def processfile(infilename):
     results={}
     base, ext =os.path.splitext(infilename)
     if ext == INFILEEXT:
         text = fetchonefiledata(infilename)
         numcolumns=len(text[0])
         for ch in TOKENS:
             results[ch] = [0]*numcolumns

Unless of course the second file doesn't have the right file extension!
In that case it would jump to process the summary with no results data.

for k,v in results.items():
         print(results)
     summary=[]
     for a,b in zip(results['E'],results['B']):
         summary.append(a+b)

Yep, that would do it!

Lina, it looks like you need to either move the initialisation of 
results above the extension check, or else move the summary check inside 
the if block.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list