By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
431,805 Members | 1,270 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 431,805 IT Pros & Developers. It's quick & easy.

Add a new column to comma delimited text file.

P: 1
Hi.. I have a file with two columns separated by comma with numerical values (sample) -
2305,11770
2306,12017
2307,9416.6
. , .
. , .
. , .

I willing to have an output file somewhat like this -
bfe,2305,hgen,,11770
bfe,2306,hgen,,12017
bfe,2307,hgen,,9416.6
and so on...

Thank you in advance...
Mar 14 '18 #1

✓ answered by Frinavale

There are a number of string manipulation methods that you can use in Python. Check out this quick reference for String Manipulation in Python.

What you could do is use the split method on each string you get from the file on the , character which would give you an array of 2 words.

Then you would make a new string by concatenating the values into the right positions.

For example:
Expand|Select|Wrap|Line Numbers
  1. oldString = "2305,11770"
  2. oldStringParts = oldString.Split(',')
  3. newString = "bfe," + oldStringParts[0] + ",hgen,," + olStringParts[1]
  4.  
There is probably a more elegant way of doing this with string replacement but I think this is the easiest to understand if you are new to programming.

Share this Question
Share on Google+
1 Reply


Frinavale
Expert Mod 5K+
P: 9,731
There are a number of string manipulation methods that you can use in Python. Check out this quick reference for String Manipulation in Python.

What you could do is use the split method on each string you get from the file on the , character which would give you an array of 2 words.

Then you would make a new string by concatenating the values into the right positions.

For example:
Expand|Select|Wrap|Line Numbers
  1. oldString = "2305,11770"
  2. oldStringParts = oldString.Split(',')
  3. newString = "bfe," + oldStringParts[0] + ",hgen,," + olStringParts[1]
  4.  
There is probably a more elegant way of doing this with string replacement but I think this is the easiest to understand if you are new to programming.
Mar 14 '18 #2

Post your reply

Sign in to post your reply or Sign up for a free account.