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

replace a set of strings in a .txt file

P: 1
hi everyone,

My problem goes like this (*.d) which can be opened using wordpad.
Now I need to replace some strings inside my file which is enclosed within double quotes.
I have to use a I/P file as a text delimited file which have two columns first column old string and the second one is new string.
As Im new to python language can some one help me how to start with it..?

Thanks in advance.
Feb 7 '12 #1
Share this Question
Share on Google+
1 Reply

bvdet
Expert Mod 2.5K+
P: 2,851
Create a dictionary from the file with 2 columns.
Expand|Select|Wrap|Line Numbers
  1. dd = {"Col 1 text 1": "Col 2 text 1", "Col 1 text 2": "Col 2 text 2"}
I might approach replacing the text like this:
Expand|Select|Wrap|Line Numbers
  1. >>> import re
  2. >>> text = 'A line in text file containing "Col 1 text 1"'
  3. >>> dd = {"Col 1 text 1": "Col 2 text 1", "Col 1 text 2": "Col 2 text 2"}
  4. >>> patt = re.compile(r'"(.+)"')
  5. >>> m = patt.search(text)
  6. >>> if m and m.group(1) in dd:
  7. ...     text = text.replace(m.group(1), dd[m.group(1)])
  8. ...     
  9. >>> text
  10. 'A line in text file containing "Col 2 text 1"'
  11. >>> 
Feb 7 '12 #2

Post your reply

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