Newbie Question

gry at ll.mit.edu gry at ll.mit.edu
Fri Aug 19 17:45:57 CEST 2005


Yes, "eval" of data from a file is rather risky.  Suppose someone gave
you
a file containing somewhere in the middle:
...
22,44,66,88,"asd,asd","23,43,55"
os.system('rm -rf *')
33,47,66,88,"bsd,bsd","23,99,88"
...

This would delete all the files in your directory!

The csv module mentioned above is the tool of choice for this task,
especially if
there are strings that could contain quotes or commas.  Doing this
right is not
at all easy.  If you really want to roll your own, and the data is
KNOWN to be fixed
and very restricted, you can do something like:

"myfile" contains:
13,2,'the rain',2.33
14,2,'in spain',2.34

for l in open('myfile'):
    x,y,comment,height = l.split(',')
    x=int(x)
    y=int(y)
    height=int(height)
    comment=comment.strip("' ") # strip spaces and quotes from front
and back

but beware this will break if the comment contains commas.

-- George




More information about the Python-list mailing list