[Tutor] The Evil eval()

Gregor Lingl glingl@aon.at
Fri, 12 Apr 2002 16:02:17 +0200



> I am getting ready to write a program that will read the contents of a
file
> and then manipulate the data.  The file consists of a single list of lists
> all on  one line.  Something like:
>
> [[1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]
>
> If I understand correctly, when I read the file in, I will get a string
and
> to make it into a list of lists, I will have to use eval().  But, I also
> know that is dangerous and if someone knew I used that for this program,
> they could really mess

If this list of lists is produced by a Python program (as some of the
answers
you got until now seem to assume): why not use pickle?

>>> import pickle
>>> f = open("pickletest.data","w")
>>> a = [[1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12,
16, 20]]
>>> pickle.dump(a,f)
>>> f.close()
>>> f = open("pickletest.data","r")
>>> b = pickle.load(f)
>>> b
[[1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]
>>>

Wouldn't this solve your problem?

Gregor