eval to dict problems NEWB going crazy !

Roel Schroeven rschroev_nospam_ml at fastmail.fm
Thu Jul 6 08:00:58 EDT 2006


manstey schreef:
> Hi,
> 
> I have a text file called a.txt:
> 
> # comments
> [('recId', 3), ('parse', {'pos': u'np', 'gen': u'm'})]
> [('recId', 5), ('parse', {'pos': u'np', 'gen': u'm'})]
> [('recId', 7 ), ('parse', {'pos': u'np', 'gen': u'm'})]
> 
> I read it using this:
> 
> filAnsMorph = codecs.open('a.txt', 'r', 'utf-8') # Initialise input
> file
> dicAnsMorph = {}
> for line in filAnsMorph:
>     if line[0] != '#': # Get rid of comment lines
>         x = eval(line)
>         dicAnsMorph[x[0][1]] = x[1][1] # recid is key, parse dict is
> value
> 
> But it crashes every time on x = eval(line). Why is this? If I change
> a.txt to:
> 
> # comments
> [('recId', 3), ('parse', {'pos': u'np', 'gen': u'm'})]
> 
> it works fine. Why doesn't it work with multiple lines? it's driving me
> crazy!

It looks like it's because of the trailing newline. When you read a file 
like that, the newline at the end of each line is still in line. You can 
strip it e.g. with rstrip, like so:

     x = eval(line.rstrip('\n'))

-- 
If I have been able to see further, it was only because I stood
on the shoulders of giants.  -- Isaac Newton

Roel Schroeven



More information about the Python-list mailing list