[Tutor] Writing long strings (that include commas) to a csv file

Kent Johnson 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:
>
>
> file1=open('myfile.csv','w')
> writer=csv.writer(file1)
>
> mylist=[ " first , txt+words , more" , " second, text + words, and more"]
> listnumbers=["0","5"]
>
> 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:
  writer.writerow([mylist[i], listnumbers[i]])

You could also use the zip() function and writerows() to do this more simply.

zip(mylist, listnumbers) returns a list of pairs:

In [3]: zip(mylist, listnumbers)
Out[3]: [(' first , txt+words , more', '0'), (' second, text + words,
and more', '5')]

This is exactly the rows you want to write to the file, so
  writer.writerows(zip(mylist, listnumbers))
will do what you want without an explicit loop.

Kent


More information about the Tutor mailing list