Python 使用双引号为特定列编写csv文件不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25056881/
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 csv file with double quotes for particular column not working
提问by Emma
I'm trying to write a csv file using python csv writer.
我正在尝试使用 python csv writer 编写一个 csv 文件。
In which one of the column value is enclosed in "" [double quotes] e.g. : 'col1' 'col2' "test", when I open the file in wordpad, the word test is expected as "test" but actual result is """test"""
其中列值之一用 "" [双引号] 括起来,例如:'col1' 'col2' "test",当我在写字板中打开文件时,单词 test 应为 "test" 但实际结果为 " ““测试”””
can someone guide for this issue.
有人可以指导这个问题。
Sample snippet of my try out:
我尝试的示例片段:
csvReader = csv.reader(iInputFile)
writer = csv.writer(open('one_1.csv', 'wb'), delimiter=',', lineterminator='\r\n')
for row in csvReader:
rawRow = []
rawRow.append('31-7-2014') #Appending Date
rawRow.append(row[0]) #Appending data
rawRow.append('\"'+'test'+'\"')
writer.writerow(rawRow)
采纳答案by GiovanniPi
try with this one
试试这个
f_writ = open('one_4.csv', 'wb')
csvReader = csv.reader(iInputFile)
writer = csv.writer(f_writ, delimiter=',',
lineterminator='\r\n',
quotechar = "'"
)
for row in csvReader:
writer.writerow(['31-7-2014',row[0],'\"text\"'])
f_writ.close()
also i find very useful this link http://pymotw.com/2/csv/, there are a lot of exemples
我也觉得这个链接非常有用 http://pymotw.com/2/csv/,有很多例子
回答by Vasily Ryabov
Probably you need to play with parameters quoting and escapechar.
可能您需要使用参数引用和转义符。
For example, modified code
例如修改代码
csvReader = csv.reader(iInputFile)
writer = csv.writer(open('one_1.csv', 'wb'), delimiter=',', lineterminator='\r\n', quoting=csv.QUOTE_NONE, escapechar='\')
for row in csvReader:
rawRow = []
rawRow.append('31-7-2014') #Appending Date
rawRow.append(row[0]) #Appending data
rawRow.append('\"'+'test'+'\"')
writer.writerow(rawRow)
will produce output like that:
将产生这样的输出:
31-7-2014,'col1',\"test\"
回答by Junk
As far as I can tell from the accepted answer from @GiovanniPi, is that the default is
据我从@GiovanniPi 接受的答案中可以看出,默认值是
quotechar= '"'
Because the expected output already has double quotes, this has to be changed to:
因为预期的输出已经有双引号,所以必须改为:
quotechar = "'"
I am not sure what you would do if you needed to have both single and double quotes as quotechar requires a 1-character string
如果您需要同时使用单引号和双引号,我不确定您会怎么做,因为 quotechar 需要一个 1 个字符的字符串

