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?
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.