delineating by comma where commas inside quotation marks don't count

equand at gmail.com equand at gmail.com
Wed Oct 24 22:18:21 EDT 2007


On Oct 25, 3:56 am, "Junior" <mlon... at verizon.net> wrote:
> I want to open a text file for reading and delineate it by comma.  I also
> want any data
> surrounded by quotation marks that has a comma in it, not to count the
> commas inside the
> quotation marks
>
> if the file testfile.txt contains the following;
>
> 5,Tuesday,"May is a spring month",Father's Day
> 1,Saturday,"June,July and August",Independance Day
>
> and I write the following program
>
> fname = open('testfile.txt', 'r')
> ct=1
> while ct != 3:
>     rd=(fname.readline())
>     filedata=rd.split(',')
>     print "var2=",filedata[2]
>     ct +=1
>
> fname.close
>
> filedata[2] will = "May is a spring month"; on the first pass and
>
> filedata[2] will = "June;  on the second pass
>
> How do I get filedata[2] to = "June,July and August" on the second pass
>
> and filedata[3] to = Independance Day

why not using csv?
but u would better put all strings into ""
else u can

r = open('file').read().splitlines()

for i in r:
    l1 = i.split(',',2)
    l2 = l1.pop().rsplit(',',1)
    print l1+l2




More information about the Python-list mailing list