Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将逗号作为普通文本写入CSV文件?(双引号方法不起作用)_Python_Csv_Text_Comma - Fatal编程技术网

Python 如何将逗号作为普通文本写入CSV文件?(双引号方法不起作用)

Python 如何将逗号作为普通文本写入CSV文件?(双引号方法不起作用),python,csv,text,comma,Python,Csv,Text,Comma,我正在使用Python在CSV文件中输出一些数据。它必须绝对在一个CSV文件,我不能使用任何其他东西,这是我的命令做的。逗号必须用作分隔符,但有时数据包含逗号,因此我在字符串周围加了双引号,并将它们放在一个字段中。到目前为止这还不错,但是当数据还包含双引号时会发生什么呢?数据中可以包含的符号没有限制。不要重新发明轮子,请使用来写出您的数据: import csv with open(outputfilename, 'wb') as outfh: writer = csv.writer(

我正在使用Python在CSV文件中输出一些数据。它必须绝对在一个CSV文件,我不能使用任何其他东西,这是我的命令做的。逗号必须用作分隔符,但有时数据包含逗号,因此我在字符串周围加了双引号,并将它们放在一个字段中。到目前为止这还不错,但是当数据还包含双引号时会发生什么呢?数据中可以包含的符号没有限制。

不要重新发明轮子,请使用来写出您的数据:

import csv

with open(outputfilename, 'wb') as outfh:
    writer = csv.writer(outfh)
    writer.writerow(['Data with , commas and nested " quotes', 'works just fine'])
您可以调整引用行为,但默认(Excel兼容)设置将为您处理逗号和嵌套引号的引用。包含引号或逗号的列将被引用,任何嵌入的引号都会加倍

演示:

看看


您是否正在使用
csv
模块?它为您管理报价。嵌套的引号在默认(Excel兼容)配置中加倍。它会做我希望它做的事情吗?在不分隔字段的情况下写入逗号?
>>> from cStringIO import StringIO
>>> import csv
>>> out = StringIO()
>>> writer = csv.writer(out)
>>> writer.writerow(['Data with , commas and nested " quotes', 'works just fine'])
>>> out.getvalue()
'"Data with , commas and nested "" quotes",works just fine\r\n'
   5.  Each field may or may not be enclosed in double quotes (however
       some programs, such as Microsoft Excel, do not use double quotes
       at all).  If fields are not enclosed with double quotes, then
       double quotes may not appear inside the fields.  For example:

       "aaa","bbb","ccc" CRLF
       zzz,yyy,xxx

   6.  Fields containing line breaks (CRLF), double quotes, and commas
       should be enclosed in double-quotes.  For example:

       "aaa","b CRLF
       bb","ccc" CRLF
       zzz,yyy,xxx


   7.  If double-quotes are used to enclose fields, then a double-quote
       appearing inside a field must be escaped by preceding it with
       another double quote.  For example:

       "aaa","b""bb","ccc"