How to insert character in csv cell in python?

2024/11/23 3:44:01

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.

Answer

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 csvwith 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 linesif len(row) > 3:try:name, surname = row[2].split(' ', 1)except ValueError as e:# No surnamename, surname = row[2], ''row[2] = namerow.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
https://en.xdnf.cn/q/120661.html

Related Q&A

How can you initialise an instance in a Kivy screen widget

I am trying to access an instance variable named self.localId in my kivy screen and it keeps saying the saying the instance doesnt exist after i have initialised it. I know I have an error In my code b…

is a mathematical operator classed as an interger in python

in python is a mathematical operator classed as an interger. for example why isnt this code workingimport randomscore = 0 randomnumberforq = (random.randint(1,10)) randomoperator = (random.randint(0,2)…

Fix a function returning duplicates over time?

I have a function here that returns a 4 digit string. The problem is that when I run the function like 500 times or more, it starts to return duplicates. How to avoid that?My Function:import random de…

Pandas method corr() use not all features

I have dataframe with shape (335539, 26). So I have 26 features. But when i use data.corr() I get a 12 x 12 matrix.What can be wrong? `

int to datetime in Python [duplicate]

This question already has answers here:Convert string "Jun 1 2005 1:33PM" into datetime(26 answers)Parsing datetime in Python..?(2 answers)Closed 5 years ago.Im receiving data from the port.…

How to extract the historical tweets from twitter API? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 5…

ValueError: invalid literal for int() with base 16: [closed]

Closed. This question needs debugging details. It is not currently accepting answers.Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to repro…

Modify list in Python [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable…

How to delete files inside hidden folder with python? [duplicate]

This question already has answers here:How can I delete a file or folder in Python?(18 answers)Closed 5 years ago.I want do delete a file, for ex. myfile.txt that is stored under a hidden folder. Is i…

Matching keywords in a dictionary to a list in Python

The following dictionary gives the word and its value:keywords = {alone: 1, amazed: 10, amazing: 10, bad: 1, best: 10, better: 7, excellent: 10, excited: 10, excite: 10}Following the dictionary are two…