user3222101
user3222101

Reputation: 1330

python : How to allow python to not add quotation marks while changing delimiter in the csv file

I have written a script to convert delimiter in the csv file from comma to pipe symbol but while doing so it doesn't remove the extra quotation marks added by csv file.

script is as follows:-

import csv

filename = "sample.csv"

with open(filename,mode='rU') as fin,open('c:\\files\\sample.txt',mode='w') as fout:

        reader= csv.DictReader(fin)
        writer = csv.DictWriter(fout,reader.fieldnames,delimiter='|')
        writer.writeheader()
        writer.writerows(reader)

case 1: Now, for example if one of the field in the csv contains "hi" hows you,good then the csv will make it as """hi" hows you,good"" and python loads it as """hi" hows you,good"" in the text file instead of "hi" hows you,good

case 2: Whereas for the fields like hi hows, you csv makes it as "hi hows,you" and after running the script it is saved as hi hows,you in the text file which is correct.

Please could you help me to solve case 1.

example csv file when you open it in notepad:-

ID,IDN,DESC,TNO
A019,1,"""Pins ""  is dangerous",2
B020,1,"""ache"",headache/fever-like",3
C021,2,stomach cancer,1
D231,3,"hair,""fall""",1

after script result:

ID|IDN|DESC|TNO
A019|1|"""Pins ""  is dangerous"|2
B020|1|"""ache"",headache/fever-like"|3
C021|2|stomach cancer|1
D231|3|"hair,""fall"""|1

i want the result as :

ID|IDN|DESC|TNO
A019|1|"Pins "  is dangerous|2
B020|1|"ache",headache/fever-like|3
C021|2|stomach cancer|1
D231|3|hair,"fall"|1

Upvotes: 1

Views: 221

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140168

that works:

writer = csv.DictWriter(fout,reader.fieldnames,delimiter='|',quoting=csv.QUOTE_NONE,quotechar="")
  • defining the quoting as "no quoting": quoting=csv.QUOTE_NONE
  • defining the quote char as "no quote char": quotechar=""

result

ID|IDN|DESC|TNO
A019|1|"Pins "  is dangerous|2
B020|1|"ache",headache/fever-like|3
C021|2|stomach cancer|1
D231|3|hair,"fall"|1

note that quoting is useful. So disabling it exposes you to the joy of "delimiters in the fields". It's up to you to make sure it's not going to happen.

Upvotes: 1

Related Questions