Problem with loading textfiles into dictionaries.

Kartic removethis.kartic.krishnamurthy at gmail.com
Sun Jan 30 20:21:54 EST 2005


mercuryprey at gmail.com said the following on 1/30/2005 7:43 PM:
> Hello,
> I want to do the following:
> 
> def do_load(self, arg):
> sitefile = file('sitelist', 'r+', 1)
> while True:
> siteline = sitefile.readline()
> site_rawlist = siteline.split()
> sitelist[site_rawlist[0]] = site_rawlist[1:]
> if len(siteline) == 0:
> break
> 
> I want to load a textfile into a dictionaries and use the first word on
> a line as the key for the list, then take the remaining words of the
> line and make them values of the key. This doesn't work:
> 
> File "ftp.py", line 57, in do_load
> sitelist[site_rawlist[0]] = site_rawlist[1:]
> IndexError: list index out of range

Hi - It looks like your code encountered a blank line when you got this 
error.

You should move "if len(siteline) == 0" part right after your readline. 
The way you have done it really does not help.

def do_load(self, arg):
     sitefile = file('sitelist', 'r+', 1)
     while True:
       siteline = sitefile.readline()
       if len(siteline) == 0:
          break
       site_rawlist = siteline.split()
       sitelist[site_rawlist[0]] = site_rawlist[1:]

Thanks,
--Kartic



More information about the Python-list mailing list