Matt Kowaleczko
Matt Kowaleczko

Reputation: 53

csv.read inserts empty field after each record - parsing issue

I am trying to parse a csv from string of the following format

'"column a";"column b";"column c"\r\n"1";"2";"3"'

Using the below code

import csv

text = '"column a";"column b";"column c"\r\n"1";"2";"3"'
csv_raw = csv.reader(text, delimiter=';')
df = []
for row in csv_raw:
    df.append(row)

However the output I'm getting when running it looks like this

[['column a'],
 ['', ''],
 ['column b'],
 ['', ''],
 ['column c'],
 [],
 [],
 ['1'],
 ['', ''],
 ['2'],
 ['', ''],
 ['3']]

I don't understand where ['', ''] after each record comes from. How do I get rid of it?

Upvotes: 0

Views: 23

Answers (1)

Matt Kowaleczko
Matt Kowaleczko

Reputation: 53

OK, I found out that using StringIO like below solves the issue.

text = StringIO('"column a";"column b";"column c"\r\n"1";"2";"3"')
csv_raw = csv.reader(text, delimiter=';')
df = []
for row in csv_raw:
    df.append(row)

Upvotes: 1

Related Questions