[Tutor] Iterating through tokens from a split command

Alan Gauld alan.gauld at blueyonder.co.uk
Fri Mar 19 16:35:51 EST 2004

Hi Vicki,

A couple of things here.

First you only ever read a single line from the file. You then iterate
over the tokens in that line but never stop - hence the index error!

You probably want to restructure it soomething like:

for line in inputfile.readlines():  #readlines, plural!
    tokens = line.split['|']
    for token in tokens:      # iterates over the tokens
        if token == '0x11':
           new = '0x02|'
        elif token == '0x03':
           outputfile.write(token + "|")


This saves all the indexing, means you don't need to check for
index errors or end of file limits. It lets Python take the
strain and makes your job easier.


Alan G.

More information about the Tutor mailing list