在一列中解析逗号分隔的数据

时间:2018-07-09 16:06:58

标签: python python-3.x

需要帮助解析我的数据,

我有这样的CSV数据:

 INPUT.csv
 col0  col1    col2    col3     col4
 blue,  eight,  line,    aaa     abc@123.com,xyz@123.com,ghi@123.com
 green, nine,   square,  bbb     sdf@123.com,wef@123.com,hft@123.com

1)我想用col4下的逗号解析数据,并写入新列col5和col6 2)我要串联col1,col2和col3,我想在每行的串联输出之前加上PR#前缀

即。我的预期结果应该是

 OUTPUT.csv
  col0      col1                 col4          col5           col6
  blue   PR# eight line   aaa    abc@123.com   xyz@123.com    ghi@123.com
  green  PR# nine  square bbb    sdf@123.com   wef@123.com    hft@123.com

到目前为止,我的代码:

 import csv

 with open('INPUT.csv', 'r') as csv_file:
 csv_reader = csv.DictReader(csv_file)

with open('OUTPUT.csv', 'w',encoding='utf-8') as new_file:
    fieldnames = ['col0','col1','col2','col3','col4','col5','col6']
    csv_writer = csv.DictWriter(new_file,lineterminator='\n' , 
  fieldnames=fieldnames)
   )

     for row in csv_reader:                    
     csv_writer.writerow({
        "col0": row["col0"],
        "col1": row["col1"] + row["co2"] +  row["3"],
        "col4": row["col4"]  
       })

0 个答案:

没有答案