tags:

views:

62

answers:

3

hi
i want to write a text to csv file, in one place I need to write comma, and I don't know how to do it in a way that won't seperate the file to anotehr cell.
f.write('1,2,3,45,The Next comma I want to write and not seperate to anoterh cell , so this sentence will bw hole,6,7,8')
any sugesstions?
ariel

A: 

This is not Python specific, but is to do with the CSV "standard".

If you want to write a control character as part of your value, you'll need to escape the value by surrounding it in double-quotes:

f.write('1,2,3,45,"The Next comma I want to write and not seperate to anoterh cell , so this sentence will bw hole",6,7,8')

Edit: Although in practice, it will be a better idea to use the CSV writer interfaces as suggested by others. It's never a good idea to embroil yourself in the implementation details when there's a ready-rolled library that abstracts this away for you.

Andrzej Doyle
+1  A: 

Use the csv module, that should handle all the escaping intricacies for you: http://docs.python.org/library/csv.html

alper
+2  A: 

Use the proper CSV writers:

>>> import csv
>>> spamWriter = csv.writer(open('eggs.csv', 'wb'))
>>> spamWriter.writerow(['Spam', 'Lovely, Spam'])

Outputs:

Spam,"Lovely, Spam"

Dominic Rodger
I got the next error : AttributeError: '_csv.writer' object has no attribute 'writer'. is there a way to do it without CSV module?
ariel
@ariel - oops. I can't type - see my edit.
Dominic Rodger
-1 Not opening csv output file in binary mode. Output on Windows: `'Spam,"Lovely, Spam"\r\r\n'`
John Machin
@John - errr - yeah, per the Python documentation - http://docs.python.org/release/2.6.4/library/csv.html#csv.writer
Dominic Rodger
@Dominic: Yes, the csv docs are deficient and misleading.
John Machin
@John - fair enough, changed.
Dominic Rodger
@Dominic: Presumably you are referring to the example. You haven't noticed the somewhat vague remark earlier: """If csvfile is a file object, it must be opened with the ‘b’ flag on platforms where that makes a difference.""". Windows is the platform where it does make a difference. Sound practice is to always use binary mode on both input and output files -- this makes the script or advice-to-newbie platform-independent.
John Machin
@John - am I right in thinking this doesn't apply in Python 3? (per http://stackoverflow.com/questions/1020053/writing-with-pythons-built-in-csv-module)
Dominic Rodger
@Dominic: Python 3.1: Reading: docs say must open file with `newline=''`. Writing: docs say nothing. Actuality is that Windows needs `newline=''` otherwise you get extra `\r`.
John Machin