Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python CSV module, special split string

Tags:

python

string

csv

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?

like image 672
Robert Pawlak Avatar asked Sep 17 '26 16:09

Robert Pawlak


1 Answers

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')
like image 90
Jon Clements Avatar answered Sep 20 '26 06:09

Jon Clements



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!