使用python将带有逗号的文本写入CSV文件的单元格中
我想将带有逗号的文本写入 CSV 文件的单元格中。
输入
'1,2,3,Hello'
CSV 中的输出应为
'1,2,3','Hello'
I want to write text with comma into a cell in CSV file.
Input
'1,2,3,Hello'
Output in CSV should be
'1,2,3','Hello'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用正确的 CSV writer:
输出:
Use the proper CSV writers:
Outputs:
这不是 Python 特有的,而是与 CSV“标准” 有关。
如果您想将控制字符写入作为值的一部分,则需要通过用双引号将其括起来来转义该值:
编辑:尽管在实践中,最好按照建议使用 CSV 编写器接口由其他人。当有一个现成的库可以为您抽象出实现细节时,让自己陷入实现细节从来都不是一个好主意。
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:
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.
因此,您可以使用引号将每个字段文本括起来。
假设输入为
['1,2,3', 'Hello']
,则 CSV 的输出应为"1,2,3", "Hello"
,您可以使用下面的代码来实现此目的。但是当文本中存在一些特殊符号,如
"
、\n
等时,你就会遇到问题。pythoncsv 库已经为你处理了所有的边缘情况。
编写 写入
可以使用 @Dominic Rodger 答案
字符串
https://stackoverflow.com/a/9157370/5238892 Python
在 Python 3 中:
2 需要稍微更改一些细节:
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.But you will encounter problems when there are some special symbols such as
"
,\n
and etc in text.The python csv library has handled all the edge cases for you.
Write to file
Can use @Dominic Rodger answer.
Write to string
From https://stackoverflow.com/a/9157370/5238892.
In Python 3:
Some details need to be changed a bit for Python 2: