Search code examples
python-3.xlistcsvdouble-quotes

Python3 producing double quoted string in CSV output


I am using Python3 to access a EST/API that produces json output. I have to scrape some data from an API call and produce a simple .csv file for another process to consume. The CSV file should not contain any quote strings.

The desired csv output is rows like this (basically a device name, and IP address and a ticket#):

devicename.domain,1.1.1.1,ticket_number

However I am getting this in my csv file:

"devicename.domain,1.1.1.1,ticket_number"

I believe the double-qoutes are coming from the way I am generating my list element, but I cannot seem to get rid of them, either in the list construction or in the csv output. I have tried various of 'quoting=csv.QUOTE_NONE' , but I can't get rid of the quotes in the CSV output file. Pretty sure the issue is with the way I am formatting the list in the first place, but I'm hitting a wall.

Here is my code:

csv_rows = []
    domain="mydomain.com"
    ticket="ticket"

    # create a nested list element that contains the data scraped from json
    for switch in switches:
        switchname = switch["switch-name"]
        switchip = switch["ip"]
        csv_rows.append([f"{switchname}.{domain},{switchip},{ticket}"])
filename = f"{ticket}.csv"

with open(filename, 'w') as csvfile:
# creating a csv writer object
csvwriter = csv.writer(csvfile)
# writing the data rows
csvwriter.writerows(csv_rows)

Solution

  • The quotes are added by the CSV writer because it thinks you want all those things in a single column so it surrounds the whole string with quotes in order to escape the commas you have put in.

    By doing the string formatting and adding commas yourself you are duplicating what the CSV module does and therefore getting unwanted behaviour. It expects an iterable such as a list for each line, it will then add the column separators and quotes itself. Try this:

    csv_rows.append([f"{switchname}.{domain}",switchip,ticket])