pythoncsvwriter

Is there a function or argument to remove quotes when writing to csv file in python


I am appending a large amount of data and writing to a csv file.

Data is a list that is appended to an example: data = ['438.0337145,438.0178423,0.0158\n', '438.0497017,438.0337145,0.01598\n']

with open(uuidCSV, 'w') as csvFile:
    wr = csv.writer(csvFile, lineterminator="\n", quoting=csv.QUOTE_ALL, delimiter=",")
    wr.writerow(data)

When I open the csv file the output is:

"438.0337145,438.0178423,0.0158
","438.0497017,438.0337145,0.01598

Using the below method creates:

with open(uuidCSV, 'w') as csvFile:
    wr = csv.writer(csvFile, lineterminator="\n", quoting=csv.QUOTE_NONE, delimiter=",", escapechar="\"")
    wr.writerow(data)

Creates:

 438.0337145",438.0178423",0.0158"
,438.0497017",438.0337145",0.01598"

Is there a way to remove the quotes so the output is:

438.0337145,438.0178423,0.0158
438.0497017,438.0337145,0.01598

Solution

  • You don't need to use pandas as advised by Mark. You can do this with what you have.

    Firstly, you will want to change quoting=csv.QUOTE_ALL to quoting=csv.QUOTE_MINIMAL for this to work.

    Secondly, your need to sort out the data list.

    Currently it thinks 438.0337145,438.0178423,0.0158\n is one string. The quotes are added automatically on output as the strings contain commas and without them it will cause problems when opening or reading the CSV.

    Either add more apostrophes to split them into individual strings, or remove the apostrophes to have floats (numbers).

    You will then need to loop over each row and print them independently.

    Try doing the following instead:

    data = [
        [438.0337145,438.0178423,0.0158],
        [438.0497017,438.0337145,0.01598]
    ]
    
    with open(uuidCSV, 'w') as csvFile:
        wr = csv.writer(
            csvFile,
            quoting=csv.QUOTE_ALL,
            delimiter=","
        )
    
        for row in data:
            wr.writerow(row)
    
    

    See the docs for more info: https://docs.python.org/3/library/csv.html