[Tutor] Writing long strings (that include commas) to a csv file
kent37 at tds.net
Thu Jan 22 21:36:49 CET 2009
On Thu, Jan 22, 2009 at 2:33 PM, Judith Flores <juryef at yahoo.com> wrote:
> Hello dear Python experts,
> How can I write a complete string (which sometimes will include many commas) to a cell in a CSV file? With the code below, what I obtain is a cell per letter of every string:
> mylist=[ " first , txt+words , more" , " second, text + words, and more"]
> for i in range(0,len(mylist)):
> writer.writerow(mylist[i] + listnumbers[i])
The argument passed to writerow() is a sequence where each element of
the sequence is one cell value. Here, you are passing a string as the
argument. A string is a sequence of characters, so you are telling
writerow() to write one character per cell.
What you want to give writerow() is a list containing the two strings
that you want placed in the two cells. Like this:
You could also use the zip() function and writerows() to do this more simply.
zip(mylist, listnumbers) returns a list of pairs:
In : zip(mylist, listnumbers)
Out: [(' first , txt+words , more', '0'), (' second, text + words,
and more', '5')]
This is exactly the rows you want to write to the file, so
will do what you want without an explicit loop.
More information about the Tutor