简体   繁体   English

使用python将带逗号的文本写入CSV文件中的单元格

[英]Write text with comma into a cell in CSV file using python

I want to write text with comma into a cell in CSV file.我想用逗号将文本写入 CSV 文件的单元格中。

Input输入

'1,2,3,Hello'

Output in CSV should be CSV 格式的输出应该是

'1,2,3','Hello'

Use the proper CSV writers :使用正确的CSV 编写器

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

Outputs:输出:

Spam,"Lovely, Spam"垃圾邮件,“可爱的,垃圾邮件”

This is not Python specific, but is to do with the CSV "standard" .这不是特定于 Python 的,而是与CSV“标准”有关。

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 separate to another cell, so this sentence will be whole",6,7,8')

Edit: Although in practice, it will be a better idea to use the CSV writer interfaces as suggested by others.编辑:尽管在实践中,最好使用其他人建议的 CSV 编写器界面。 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.当有一个现成的库可以为您抽象出来时,将自己卷入实现细节绝不是一个好主意。

Each line of the file is a data record.文件的每一行都是一条数据记录。 Each record consists of one or more fields, separated by commas.每条记录由一个或多个字段组成,以逗号分隔。

The basic idea of separating fields with a comma is clear, but that idea gets complicated when the field data may also contain commas or even embedded line-breaks.用逗号分隔字段的基本思想很清楚,但是当字段数据也可能包含逗号甚至嵌入式换行符时,这个想法就变得复杂了。

CSV implementations may not handle such field data, or they may use quotation marks to surround the field. CSV 实现可能不处理此类字段数据,或者它们可能使用引号将字段括起来。 -- From https://en.wikipedia.org/wiki/Comma-separated_values -- 来自https://en.wikipedia.org/wiki/Comma-separated_values

So you can use quotation marks to surround the each field text.因此,您可以使用引号将每个字段文本括起来。

Suppose the input is ['1,2,3', 'Hello'] , the output to CSV should be "1,2,3", "Hello" , you can use codes below to achieve this.假设输入是['1,2,3', 'Hello'] ,CSV 的输出应该是"1,2,3", "Hello" ,你可以使用下面的代码来实现。

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

But you will encounter problems when there are some special symbols such as " , \n and etc in text.但是当文本中出现"\n等特殊符号时就会遇到问题。

The python csv library has handled all the edge cases for you. python csv 库已经为您处理了所有边缘情况。

Write to file写入文件

Can use @Dominic Rodger answer.可以使用@Dominic Rodger 的回答。

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

Write to string写入字符串

From https://stackoverflow.com/a/9157370/5238892 .来自https://stackoverflow.com/a/9157370/5238892

In Python 3:在 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 changed a bit for Python 2: 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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM