15

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)
Emma
  • 617
  • 2
  • 12
  • 29

4 Answers4

18

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

GiovanniPi
  • 260
  • 1
  • 8
  • 2
    Thanks for the link, really useful. Your code works exactly as I want. But can you please explain it for my better understanding. Thanks a lot. :) – Emma Jul 31 '14 at 13:17
4

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\"
Vasily Ryabov
  • 9,386
  • 6
  • 25
  • 78
  • 1
    Thank you for the reply, but I just want string in double quotes. No any other character,not even space. – Emma Jul 31 '14 at 13:08
3

More generally, if you need to save your CSV file with every column within double quotes

with open('Data/with_quotes.csv', 'wt') as fr:
    csv_writer = csv.writer(fr, quoting=csv.QUOTE_ALL)
    
    with open('without_quotes.csv', 'rt') as f:
        csv_reader = csv.reader(f, skipinitialspace=True, doublequote=False)

        for row in csv_reader:
            csv_writer.writerow(row)
Shankar ARUL
  • 12,642
  • 11
  • 68
  • 69
0

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

Junk
  • 83
  • 8