python 写数据csv文件,将数据写入CSV文件Python

My data looks like below

['[\'Patient, A\', \'G\', \'P\', \'RNA\']']

Irrespective of the brackets, quotes and back slashes, I'd like to separate the data by ',' and write to a CSV file like below

Patient,A,G,P,RNA

Mentioning delimiter = ',' has done no help. The output file then looks like

['Patient, A','G','P','RNA']

all in a single cell. I want to split them into multiple columns. How can I do that?

Edit - Mentioning quotechar='|' split them into different cells but it now looks like

|['Patient, A','G','P','RNA']|

Edit-

out_file_handle = csv.writer(out_file, quotechar='|', lineterminator='\n', delimiter = ",")

data = ''.join(mydict.get(word.lower(), word) for word in re.split('(\W+)', transposed))

data = [data,]

out_file_handle.writerow(data)

transposed:

['Patient, A','G','P','RNA']

data:

['[\'Patient, A\', \'G\', \'P\', \'RNA\']']

And it has multiple rows, the above is one of the rows from the entire data.

解决方案

Python has a CSV writer. Start off with

import csv

Then try something like this

with open('new.csv', 'wb') as write_file:

file_writer = csv.writer(write_file)

for i in range(data):

file_writer.writerow([x for x in data[i]])

Edit:

You might have to wrangle the data a bit first before writing it, since it looks like its a string and not actually a list. Try playing around with the split() function

list = data.split()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值