Search code examples
pythonpython-2.7csvdouble-quotes

Write in to CSV file without double quotes


I have my input file format as:

 K100, radioactive 126, liquid 503, pour 2014, onto 992, sealed 9876, drum 15306
 K200, radioactive 558, liquid 1569, pour 5325, onto 772, sealed 9773, drum 10430
 K300, radioactive 463, liquid 1360, pour 981, onto 825, sealed 5872, drum 11459

I am using this code:

import csv
a = open("input.txt")
data = a.read()
data1 = data.split(',')
rf = open("output.csv",'wb')
wr = csv.writer(rf,dialect='excel')
wr.writerow(data1)

I am getting this kind of a pattern when I open the csv file:

K100     radioactive 126     liquid 503  pour 2014   onto 992    sealed 9876    " drum 15306
K200"    radioactive 558     liquid 1569     pour 5325   onto 772    sealed 9773    " drum 10430
K300"    radioactive 463     liquid 1360     pour 981    onto 825    sealed 5872    " drum 11459
"

Everything is ok but I do not want the double quotes to appear everywhere. I want to remove that. I am not able to fix this. Please help!

That is,

Expected Output:

K100     radioactive 126     liquid 503      pour 2014   onto 992    sealed 9876     drum 15306
K200     radioactive 558     liquid 1569     pour 5325   onto 772    sealed 9773     drum 10430
K300     radioactive 463     liquid 1360     pour 981    onto 825    sealed 5872     drum 11459

Solution

  • Based on the input you gave, why don't you just simply use the csv reader and then write back out to the format you want? It seems to be already comma delimited, so the reader should be fine to use:

    import csv
    a = open("d.txt")
    data = csv.reader(a)
    
    rf = open("output.csv", 'wb')
    wr = csv.writer(rf, dialect='excel')
    for i in data:
        wr.writerow(i)