将1列CSV拆分为3个列/列

时间:2015-05-10 20:17:52

标签: python list csv

我有一个CSV文件,其中一列包含以下数据类型:500封电子邮件:

[['Lindsey Jessica <xyz@icloud.com>'], 
['Jonathan Bob <a@xyz.edu>'],
['Homer Simpson <b@xyz.edu>']

我需要将它放在一个新的CSV文件中,其中3列用

分隔
**FirstName** **LastName** **Email**

我设法将CSV的一列分成3个元素的列表:

["['Lindsey", 'M', "<lindsey@icloud.com>']", "['Jonathan", 'Andre', "<andre@xyz.edu>']", "['Greg", 'Kohl', "<kohls@gmail.com>']",...etc]

但现在我需要它写入CSV看起来像这样:

      Col 1    Col 2   Col 3
Row 1 John     Doe     <mail-noreply@google.com>
Row 2 Joe      Doe     <mail-noreply@google.com>
Row 3 Jacob    Doe     <mail-noreply@google.com>

最好摆脱那些&#34;&lt; &GT;&#34;电子邮件上的标志,以便我可以将它们导入mailchimp。我无法弄清楚如何将我的列表写入3列但是..

我的代码:

import csv

filename = ('email_list1.csv')

with open(filename, 'rt', encoding="utf-8") as f:
    reader = csv.reader(f)
    email_list = list(reader)
    email_list = (' '.join(str(v) for v in email_list)) ## Convert to string
    email_list = email_list.split() #Split into seperate elements in a list: first, last, email

## Trying to print out in columns instead of rows
out = open('email_list2.csv', 'w')
for element in email_list:
    out.write(element)
    #print (element)
    out.write('\n')
out.close()

我尝试使用zip功能无效,所以我不确定最好的方法是分成三个列表,如

firstname = []
lastname = []
email = []

或者只是将它们写入3列。感谢

3 个答案:

答案 0 :(得分:1)

async

答案 1 :(得分:0)

您的原始csv文件由空格分隔,您可以设置delimiter=" "然后将该行写入另一个csv文件,使用str.strip删除<>

import csv
with open("in.csv", 'rt') as f,  open('out.csv', 'wb') as out:
    wr = csv.writer(out)
    r = csv.reader(f, delimiter=" ")
    for row in r:
        row[2] = row[2].strip("<>")
        wr.writerow(row)

输出:

Lindsey,Jessica,xyz@icloud.com
Jonathan,Bob,a@xyz.edu
Homer,Simpson,b@xyz.edu

答案 2 :(得分:-1)

使用csv.writer

...
writer = csv.writer(out, delimiter=',')
...
  writer.writerow(element)

您还可以使用element[2].strip(['<', '>'])删除&lt;&gt;