write csv file with double quotes for particular column not working

前端 未结 3 1440
执念已碎
执念已碎 2021-01-11 16:43

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

相关标签:
3条回答
  • 2021-01-11 17:14

    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\"
    
    0 讨论(0)
  • 2021-01-11 17:19

    As far as I can tell from the accepted answer from @GiovanniPi, is that the default is

    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

    0 讨论(0)
  • 2021-01-11 17:31

    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

    0 讨论(0)
提交回复
热议问题