[Tutor] Help with files

Michael P. Reilly arcege@shore.net
Mon, 12 Jun 2000 15:39:43 -0400 (EDT)


> 
> On Mon, Jun 12, 2000 at 03:21:42PM -0300, Gustavo Passos Tourinho wrote:
> > I need read a line from a file, and pass to a method.
> > For example
> > 
> > file example.txt
> > (('q0','a'),'q1')
> > (('q0','b'),'q2')
> > (('q0','c'),'q3')
> > 
> > I need put this line into a tuples like...
> > ('q0','a'): 'q1' ....
> > 
> > when I do this
> > line=f.readline()
> > 
> > line comes iqual to "(('q0','a'), 'q1')"
> 
> Actually, it will usually have a \n at the end too.
> 
> > Finally my question :)
> > 
> > How can i took off this damn " to put the line into a tuples
> 
> The easiest way is eval().
> 
> >>> line = "(('q0','a'),'q1')"
> >>> eval(line)
> (('q0','a'),'q1')
> >>>
> 
> But you have to be careful if other people can make those files. Since line
> could be any Python expression, it could be a command to remove all your
> files, that sort of thing. But if the files are always going to be simple
> lines like that, eval() will work fine.

The easiest way around this is: eval(line, {'__builtins__': {}})
This is so the input line cannot call internal commands.

Also, note that the input (after evaluation from the string) would be
a tuple of tuples, not a dictionary pair like you are asking about.

>>> f = eval(line, {'__builtins': {}})
>>> try:
...   key, value = f
...   dict[key] = value
... except ValueError:
...   print "not a two-ple"
...
>>> dict
{('q0', 'a'): 'q0'}
>>>

This seems more like what you were asking for?

  -Arcege

-- 
------------------------------------------------------------------------
| Michael P. Reilly, Release Manager  | Email: arcege@shore.net        |
| Salem, Mass. USA  01970             |                                |
------------------------------------------------------------------------