reading a list from a file

Jordan Rastrick jrastrick at student.usyd.edu.au
Mon Jun 20 18:32:46 EDT 2005


If you decide to steer clear of eval, the following comes close to what
you want, and is somewhat Pythonic (I feel):

def back_to_list(str):
   return str.strip("[]").split(", ")

>>> s = "[1, 2, 3, 4, 5, 6]"
>>> back_to_list(s)
['1', '2', '3', '4', '5', '6']

So parsing the list structure is pretty easy. The problem is the list
elements are still in string form.

If they're only integers like in this example, you're fine. If they're
arbitrary objects, on the other hand, well then you may need eval after
all.

Question is, how did they get printed to a file in this form in the
first place?




More information about the Python-list mailing list