write csv file with double quotes for particular column not working

邮差的信 提交于 2019-12-01 01:06:33

问题


I'm trying to write a csv file using python csv writer.

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"""

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)

回答1:


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




回答2:


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\"


来源:https://stackoverflow.com/questions/25056881/write-csv-file-with-double-quotes-for-particular-column-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!