I need a script that can take a CSV file with that has a column of semicolon-delimited attributes, and break it into multiple rows to normalize that multi-valued attribute? Here is the scenario:
Current:
John,Doe,"Foo1;Bar1;Foo2;Bar2"
Target:
John,Doe,Foo1
John,Doe,Bar1
John,Doe,Foo2
John,Doe,Bar2
Edit (Answered): Avinash's answer was easy, sufficient and, as I noted in the comments, only required a few changes. The following update (apologize in advance for my poor scripting), updated Avinash's answer to work with Python 2.4 and accommodate N number of columns. Disclaimer: this will still only work if the last column is the multi-valued one, but a few loops and if/elses could resolve that if anyone wanted.
#!/usr/bin/python3
import csv
import sys
fil = sys.argv[1]
f = open(fil)
try:
reader = csv.reader(f)
for i in reader:
l = []
for x in i:
if ';' in x:
m = x.split(';')
l.append(m)
splitCol = len(l)-1
else:
l.append(x)
for j in l[splitCol]:
strng = ''
for colCount in range(len(l)):
if colCount != splitCol and colCount == 0:
strng = strng+''.join(i[colCount])
elif colCount != splitCol and colCount != 0:
strng = strng+','+''.join(i[colCount])
elif colCount == splitCol and colCount == 0:
strng = strng+j
else:
strng = strng+','+j
print(strng)
finally:
f.close()
,
or newlines in quoted fields?)