[Tutor] Re ading List from File

Shashwat Anand anand.shashwat at gmail.com
Wed Nov 11 14:09:56 CET 2009


<snip>


Samir-16 wrote:
> >
> > Hi Everyone,
> >
> > I am trying to read a comma-delimitted list ("aaa","bbb","ccc") from a
> > text
> > file and assign those values to a list, x, such that:
> >
> > x = ["aaa", "bbb", "ccc"]
> >
> > The code that I have come up with looks like this:
> >
> >>>> x = []
> >>>> f = open(r'c:\test.txt', 'r')
> >>>> x.extend(f.readlines())
> >>>> x
> > ['"aaa","bbb","ccc"']
> >
> > If you look closely, there is an extra pair of single quotes (') that
> > encapsulates the string.  Therefore, len(x) returns 1, instead of 3.  Is
> > there a function to "separate" this list out?  I hope my question makes
> > sense.
>

Simply use split().
I appended these lines at the end of your piece of code,

>>> y = x[0].split(',')
>>> y
['"aaa"', '"bbb"', '"ccc"']
>>> len(y)
3
the reason for extra quotes is due to the fact that string is "aaa" and not
aaa and strings are encapsulated with "" and hence the extra quote.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20091111/f4d7ba67/attachment.htm>


More information about the Tutor mailing list