Home > Blockchain >  How to remove double quotes from a csv file
How to remove double quotes from a csv file

Time:09-02

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 csv 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)

CodePudding user response:

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)
  • Related