[Tutor] Reading List from File

Emad Nawfal (عماد نوفل) emadnawfal at gmail.com
Thu Jul 31 15:33:37 CEST 2008


On Thu, Jul 31, 2008 at 8:07 AM, S Python <spython01 at gmail.com> 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.
>
> Thanks in advance.
>
> Samir
>
>
This is an answer by a novice, and it may not be the best around;
Why don't you first get rid of the quotation marks and then split on the
comma:

>>> f = open(r'c:\test.txt', 'r').read().replace('"', '')
>>> x = []
>>> x.extend(f.split(","))
>>> x
['aa', ' bb', ' cc']
>>> len(x)
3

>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
لا أعرف مظلوما تواطأ الناس علي هضمه ولا زهدوا في إنصافه كالحقيقة.....محمد
الغزالي
"No victim has ever been more repressed and alienated than the truth"

Emad Soliman Nawfal
Indiana University, Bloomington
http://emnawfal.googlepages.com
--------------------------------------------------------
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080731/0029f5d2/attachment.htm>


More information about the Tutor mailing list