Pass List to Data Rows

I have data in a file:

196465702|91017022|['95592022', '96094942', '100920382']|91048702

and I will convert the data as shown below:

196465702|91017022|95592022|91048702
196465702|91017022|96094942|91048702
196465702|91017022|100920382|91048702

So far I have been trying to write this. Not sure if this is an accurate and optimal way. Moreover, if there is a list in the 4th column and 5th column, etc., it becomes difficult to loop for each column and join back.

import csv
with open('sample.out','r') as x:
  f = csv.reader(x,delimiter='|')
  for row in f:
    s = row[2].translate(None,"'")
    #print s.split(',')
    for t in s.split(','):
      print row[0]+'|'+row[1]+'|'+t.translate(None,"[None]")+'|'+row[3].translate(None,"None")

Is there a better way to write this? Also, if the data has List in multiple columns, is there a better way to identify and transpose rows and join the rest of the data?

+3
source share
1 answer

I would do it like this

data = "196465702|91017022|['95592022', '96094942', '100920382']|91048702"
from ast import literal_eval
first, second, third, last = data.split("|")
third = literal_eval(third)
for item in third:
    print "{}|{}|{}|{}".format(first, second, item, last)

Output

196465702|91017022|95592022|91048702
196465702|91017022|96094942|91048702
196465702|91017022|100920382|91048702
+2
source

All Articles