本文介绍了如何在python的csv单元格中插入字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python的新手.这是我的csv文件:

I'm new with python. Here is my csv file :

data;data;name surname; data; data
data;data;name surname; data; data
data;data;name surname; data; data
data;data;name surname; data; data

我想做的是插入;"使名称和姓氏像这样两列:

The thing that I want to do is to insert ";" to make name and surname 2 columns like that :

data;data;name;surname; data; data
data;data;name;surname; data; data
data;data;name;surname; data; data
data;data;name;surname; data; data

但是困难的是,有时存在多个空间,例如:

But the hard thing is sometimes there is more than one space, like that :

data;data;name surname surname2; data
data;data;name surname surname2 surname3; data

我只想替换第一个空格,而不是那样:

And I just want to replace the first spaces, not all like that :

data;data;name;surname surname2; data
data;data;name;surname surname2 surname3; data

这是我的代码,但它替换了每个空格:

Here is my code but it replaces every space:

def modify_rows():
    with open("result2.csv","rb") as source:
          rdr= csv.reader(source, delimiter=';')
          with open("result3.csv","wb") as result:
             wtr= csv.writer(result,delimiter=';')
                 for r in rdr:
                    rowname = r[3].replace(' ', ';')
                   wtr.writerow((r[0],r[1],rowname,r[2]))

希望我能找到帮助.

推荐答案

您可以告诉Python的 split() 通过传递maxsplit参数在给定数量的匹配后停止.因此,在您的情况下,您只需要按如下所示在第一个空格之后进行分割:

You can tell Python's split() to stop after a given number of matches by passing a maxsplit parameter. So in your case you just need to split after the first space as follows:

import csv

with open('input.csv', 'rb') as f_input, open('output.csv', 'wb') as f_output:
    csv_output = csv.writer(f_output, delimiter=';')

    for row in csv.reader(f_input, delimiter=';'):
        # Skip empty lines
        if len(row) > 3:
            try:
                name, surname = row[2].split(' ', 1)
            except ValueError as e:
                # No surname
                name, surname = row[2], ''

            row[2] = name
            row.insert(3, surname)
            csv_output.writerow(row)

因此对于具有以下内容的输入:

So for an input with:

data;data;name surname1 surname2;data;data
data;data;name surname;data;data
data;data;name surname;data;data
data;data;name surname;data;data

您会得到:

data;data;name;surname1 surname2;data;data
data;data;name;surname;data;data
data;data;name;surname;data;data
data;data;name;surname;data;data

这篇关于如何在python的csv单元格中插入字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 08:48