0

I am trying to split a specific column of csv into multiple column and then appending the split values at the end of each row.

I wanted to split second column on ',' and '.' and ';' and then append to each row respective values.

import csv
fOpen1=open('Meta_D1.txt')

reader=csv.reader(fOpen1)
mylist=[elem[1].split(',') for elem in reader]
mylist1=[]

for elem in mylist:
    mylist1.append(elem)


#writing to a csv file
with open('out1.csv', 'wb') as fp:
    myf = csv.writer(fp, delimiter=',')
    myf.writerows(mylist1)

Can someone guide me further?

3
  • pls show the example of input and expected output. I can't understand what exactly you want. Commented Nov 29, 2016 at 19:44
  • are the values in elem[1] always the same length after splitting? Commented Nov 29, 2016 at 19:46
  • @RajatHanda I can't open the link and don't really want to download anything. So psl include couple lines of example in your question. That would be enough. Commented Nov 29, 2016 at 19:53

1 Answer 1

1

To split with multiple delimiters, you can use regex:

import re
re.split(';|, |\. ', col_2)

Example from your file:

>>> col_2 = "Braund, Mr. Owen Harris;22"
>>> re.split(';|, |\. ', col_2)
['Braund', 'Mr', 'Owen Harris', '22']

Using this, try the following to achieve your desired output:

import csv
import re

with open('out1.csv', 'wb') as fp:
    with open('Meta_D1.txt', 'r') as f:
        reader = csv.reader(f)
        next(reader)
        for line in reader:
            cols = re.split(';|, |\. ', line[1])
            del line[1]
            line.extend(cols)
            myf = csv.writer(fp, delimiter=',')
            myf.writerow(line)
Sign up to request clarification or add additional context in comments.

2 Comments

You are right. But it is basically copying mylist to mylist1. So it is useless to have mylist1.
Thank You, @ettanany . This is what I need

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.