[Tutor] Lists in a file

Kent Johnson kent37 at tds.net
Sun Apr 26 21:04:44 CEST 2009

On Sun, Apr 26, 2009 at 2:18 PM, Robert Berman <bermanrl at cfl.rr.com> wrote:
> David,
> You are processing a text file. It is your job to treat it as a file
> comprised of lists. I think what you are saying is that each line in the
> text file is a list. In that case
> for line in fileobject:
>   listline = list(line)
> Now, listline is a list of the text items in line.

listline will be a list of all the characters in the line, which is
not what the OP wants.

If the list will just contain quoted strings that don't themselves
contain commas you can do something ad hoc:
In [2]: s = "['a','b','c']"

In [5]: [ str(item[1:-1]) for item in s[1:-1].split(',') ]
Out[5]: ['a', 'b', 'c']

In Python 3 you can use ast.literal_eval().
>>> import ast
>>> s = "['a','b','c']"
>>> ast.literal_eval(s)
['a', 'b', 'c']

You can use these recipes:


More information about the Tutor mailing list