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
views:
62answers:
3
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
2010-08-13 10:11:01
+1
A:
Use the csv module, that should handle all the escaping intricacies for you: http://docs.python.org/library/csv.html
alper
2010-08-13 10:11:01
+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
2010-08-13 10:11:04
I got the next error : AttributeError: '_csv.writer' object has no attribute 'writer'. is there a way to do it without CSV module?
ariel
2010-08-13 10:24:52
@ariel - oops. I can't type - see my edit.
Dominic Rodger
2010-08-13 10:27:07
-1 Not opening csv output file in binary mode. Output on Windows: `'Spam,"Lovely, Spam"\r\r\n'`
John Machin
2010-08-13 11:54:44
@John - errr - yeah, per the Python documentation - http://docs.python.org/release/2.6.4/library/csv.html#csv.writer
Dominic Rodger
2010-08-13 11:56:25
@Dominic: Yes, the csv docs are deficient and misleading.
John Machin
2010-08-13 11:59:29
@John - fair enough, changed.
Dominic Rodger
2010-08-13 12:04:26
@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
2010-08-13 12:07:52
@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
2010-08-13 12:34:24
@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
2010-08-13 21:11:19