0

I'm trying to parse a CSV file like this one:

="meet_name",="swim_time",="swim_date"

this is the code I have so far:

import csv

 with open('Report.csv', 'r') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter='=', quotechar='"')

    for line in csv_reader:
        print(line)

but when I print it to the screen the comma still there:

['', 'meet_name,', 'swim_time,', 'swim_date,']

How could I parse it without the coma at the end?

1 Answers1

0

I think the CSV sample you gave doesn't matche the sample output: there's no comma after "swim_date", but it's there in the output. I also wonder why CSV lines start with an equal sign. To me, the equal signs might be the characters that shouldn't be there.

Actually, if I test your code with a comma separator, it outputs:

['="meet_name"', '="swim_time"', '="swim_date"']

which is more consistent. But, as the equal sign is outside the quotechar, those one are not detected. But if everything if formatted that way, something like that would to the job:

import csv

with open('Report.csv', 'r') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',', quotechar='"')

    for line in csv_reader:
        newLine = []

        for element in line:
            if element[:2]+element[-1] != '=""':
                raise RuntimeError("Unhandled formatting")

            newLine.append(element[2:-1])

        print(newLine)
VincentRG
  • 94
  • 4