使用python将带逗号的文本写入CSV文件中的单元格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3475856/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Write text with comma into a cell in CSV file using python
提问by ariel
I want to write text with comma into a cell in CSV file.
我想用逗号将文本写入 CSV 文件的单元格中。
Input
输入
'1,2,3,Hello'
'1,2,3,Hello'
Output in CSV should be
CSV 格式的输出应该是
'1,2,3','Hello'
'1,2,3','Hello'
回答by Andrzej Doyle
This is not Python specific, but is to do with the CSV "standard".
这不是 Python 特定的,而是与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 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. 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.
编辑:尽管在实践中,按照其他人的建议使用 CSV 编写器接口将是一个更好的主意。当有一个现成的库为您抽象出来时,将自己卷入实现细节永远不是一个好主意。
回答by Dominic Rodger
Use the proper CSV writers:
使用正确的CSV 编写器:
>>> import csv
>>> spamWriter = csv.writer(open('eggs.csv', 'wb'))
>>> spamWriter.writerow(['Spam', 'Lovely, Spam'])
Outputs:
输出:
Spam,"Lovely, Spam"
垃圾邮件,“可爱,垃圾邮件”
回答by Simin Jie
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. -- From https://en.wikipedia.org/wiki/Comma-separated_values
文件的每一行都是一条数据记录。每条记录由一个或多个字段组成,以逗号分隔。
用逗号分隔字段的基本思想很清楚,但是当字段数据还可能包含逗号甚至嵌入的换行符时,这个想法就变得复杂了。
CSV 实现可能不处理此类字段数据,或者它们可能使用引号将字段括起来。-- 来自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 ", \nand 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'

