[Tutor] Tutor Digest, Vol 53, Issue 110

kinuthiA muchanE muchanek at gmail.com
Thu Jul 31 17:47:33 CEST 2008



> 
> Message: 5
> Date: Thu, 31 Jul 2008 09:07:22 -0400
> From: "S Python" <spython01 at gmail.com>
> Subject: [Tutor] Reading List from File
> To: tutor at python.org
> Message-ID:
>         <50a597410807310607l189115a5qa3335e706d33c1f8 at mail.gmail.com>
> Content-Type: text/plain; charset="iso-8859-1"
> 
> 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.
I think you are better off using the csv module. If you have a comma
separated file you could...

import csv
reader = csv.reader(open("some.csv", "rb"))
for row in reader:
    print row
I yanked this straight out of the Python Reference Library :)
> 
> Thanks in advance.
> 
> Samir
> -------------- next part --------------
> An HTML attachment was scrubbed...
> URL:
> <http://mail.python.org/pipermail/tutor/attachments/20080731/9f329f25/attachment-0001.htm>
> 



More information about the Tutor mailing list