如何使用Python合并CSV字符串中的字段? [英] How can I merge fields in a CSV string using Python?

查看:766
本文介绍了如何使用Python合并CSV字符串中的字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Python在CSV文件的每一行合并三个字段。这将是简单的,除了一些字段由双引号包围,并包括逗号。这里是一个例子:

I am trying to merge three fields in each line of a CSV file using Python. This would be simple, except some of the fields are surrounded by double quotes and include commas. Here is an example:

,,Joe,Smith,New Haven,CT,"Moved from Portland, CT",,goo,

有没有简单的算法可以合并这个格式的每一行的字段7-9?

Is there a simple algorithm that could merge fields 7-9 for each line in this format? Not all lines include commas in double quotes.

感谢。

推荐答案

这样的东西?

import csv
source= csv.reader( open("some file","rb") )
dest= csv.writer( open("another file","wb") )
for row in source:
    result= row[:6] + [ row[6]+row[7]+row[8] ] + row[9:]
    dest.writerow( result )






示例

>>> data=''',,Joe,Smith,New Haven,CT,"Moved from Portland, CT",,goo,
... '''.splitlines()
>>> rdr= csv.reader( data )
>>> row= rdr.next()
>>> row
['', '', 'Joe', 'Smith', 'New Haven', 'CT', 'Moved from Portland, CT', '', 'goo', '' ]
>>> row[:6] + [ row[6]+row[7]+row[8] ] +  row[9:]
['', '', 'Joe', 'Smith', 'New Haven', 'CT', 'Moved from Portland, CTgoo', '']

这篇关于如何使用Python合并CSV字符串中的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆