Robert Pawlak
Robert Pawlak

Reputation: 529

Python CSV module, special split string

i had an unique problem. I have code:

with open("test.csv", "r") as csvFile:
reader = csv.reader(csvFile, skipinitialspace=True)
for row in reader:
    for obj in row:
        print(obj)

and exemplary csv file:

anotherCommand, e=5, f=6, g=7, h=9, test="aaa, bbb, ggggg"

i want split this string in this way:

anotherCommand
e=5
f=6
g=7
h=9
test="aaa, bbb, ggggg"

but code which i was presented, split these string in this way:

anotherCommand
e=5
f=6
g=7
h=9
test="aaa
bbb
ggggg"

This is wrong solution this problem. I saw topic like: Why is the Python CSV reader ignoring double-quoted fields? or How can i parse a comma delimited string into a list (caveat)?

But this example is different, and these examples not come up my expectation. Someone have idea?

Upvotes: 3

Views: 278

Answers (1)

Jon Clements
Jon Clements

Reputation: 142116

You could possibly make use of shlex.split here:

import shlex

with open('test.csv') as fin:
    for line in fin:
        row = [col.rstrip(',') for col in shlex.split(line)]
        print(*row, sep='\n')

Upvotes: 1

Related Questions