Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

How to insert character in csv cell in python?

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]))    

Hope I can find help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

You would get:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...