Search code examples
pythoncsv

How to remove double quotes from a CSV file


I'm still quite new to Python and I have been trying to figure out a way to remove the double quotes and split the fields within the quotes from a OSV file.

For example: the imported data from the CSV file consists of a row with the following:

data: 1 ; "2;3" ; "4;5" ; 6

The desired output I would be going for would be:

output: 1 , 2 , 3 , 4 , 5 , 6

I have tried using the following code to achieve this although it doesn't recognize the semicolon within the quotes as a delimiter:

with open('file.csv','r') as csv_file:
csv_reader = csv.reader(csv_file,delimiter=';',quoting=csv.QUOTE_NONE,skipinitialspace=True, escapechar='"' )
next(csv_reader)
output = ""
for line in csv_reader:
        output +=  line[0] + ',' + line[1]+ ',' + line[2] + ',' + line[3] + ',' + line[4] + ',' + line[5]
print(output)

Solution

  • import csv
    
    with open('file.csv','r') as csv_file:
        csv_reader = csv.reader(csv_file,delimiter=';',quoting=csv.QUOTE_NONE, skipinitialspace=True)
        output = ""
        # iterate over every line of the csv
        for line in csv_reader:
            # iterate over each element of the line
            for i in range(len(line)):
                line[i] = line[i].strip(" ").strip("\"")
            output += ", ".join(line) + "\n"  # remove the "\n" if you want no return character
        print(output)