Robert Pawlak Robert Pawlak - 1 year ago 61
Python Question

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?

Answer Source

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')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download