Writing semicolon text to a cell in a CSV file using python

I want to write comma text in a cell in a CSV file.

Enter

'1,2,3,Hello'

CSV output should be

'1,2,3','Hello'

+5
source share
3 answers

Use CSV writers :

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

Outputs:

Spam, "Lovely, Spam"

+11
source

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

If you want to write a control character as part of your value, you will 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')

: CSV, . , , .

+5

. , .

, , .

CSV , . - https://en.wikipedia.org/wiki/Comma-separated_values

, , .

Suppose that the input ['1,2,3', 'Hello'], output in the CSV should be "1,2,3", "Hello", for this you can use the codes below.

>>> ",".join('"{0}"'.format(s) for s in ['1,2,3', 'Hello'])
'"1,2,3","Hello"'

But you will encounter problems when there are special characters in the text, such as ", \netc.

The python csv library handled all edge cases for you.

Write to file

May use @Dominic Rodger's answer.

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

Write to string

From fooobar.com/questions/15185 / ... .

In Python 3:

>>> import io
>>> import csv
>>> output = io.StringIO()
>>> csvdata = [1,2,'a','He said "what do you mean?"',"Whoa!\nNewlines!"]
>>> writer = csv.writer(output, quoting=csv.QUOTE_NONNUMERIC)
>>> writer.writerow(csvdata)
59
>>> output.getvalue()
'1,2,"a","He said ""what do you mean?""","Whoa!\nNewlines!"\r\n'

Some details need to be slightly modified for Python 2:

>>> output = io.BytesIO()
>>> writer = csv.writer(output)
>>> writer.writerow(csvdata)
57L
>>> output.getvalue()
'1,2,a,"He said ""what do you mean?""","Whoa!\nNewlines!"\r\n'
0
source

All Articles