[Tutor] Lists in a file

David Holland davholla2002 at yahoo.co.uk
Mon Apr 27 22:21:58 CEST 2009


Thanks for all the suggestions.  I will have to try this.

--- On Sun, 26/4/09, Kent Johnson <kent37 at tds.net> wrote:

From: Kent Johnson <kent37 at tds.net>
Subject: Re: [Tutor] Lists in a file
To: "Robert Berman" <bermanrl at cfl.rr.com>
Cc: "David Holland" <davholla2002 at yahoo.co.uk>, "tutor python" <tutor at python.org>
Date: Sunday, 26 April, 2009, 8:04 PM

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:
http://code.activestate.com/recipes/511473/
http://code.activestate.com/recipes/364469/

Kent



      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090427/d147c9d5/attachment.htm>


More information about the Tutor mailing list