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

search and replace with line in document

P: 8
I am trying to write a code that searches and replaces with a line in the document. i have:

import re
x = open(r'F:\1\xxx.txt')
string = open(r'F:\1\xxx.txt').read()
Lines = x.readlines()
new_str = re.sub('zzz1', (Lines[0]) , string)

open(r'F:\1\xxx2.txt', 'w').write(new_str)

in xxx1 document i have written for testing:
1
2
3
4
5
6
7
8
9
10
zzz1
11

but the output I get in xxx2 document is:
1
2
3
4
5
6
7
8
9
10
1

11

can i have zzz1 replaced without the empty line to follow?
and how can i do it again say if wanting to replace a zzz2 with line 2?
Oct 14 '17 #1

✓ answered by chickflick91

working solution:

import re
x = open(r'F:\1\xxx.txt')
Lines = x.readlines()


repldict = {'zzz1':(Lines[0]).strip(), 'zzz2':(Lines[1]).strip()}
def replfunc(match):
return repldict[match.group(0)]

regex = re.compile('|'.join(re.escape(x) for x in repldict))
with open(r'F:\1\xxx.txt') as fin, open(r'F:\1\xxx2.txt','w') as fout:
for line in fin:
fout.write(regex.sub(replfunc,line))

Share this Question
Share on Google+
2 Replies


Expert 100+
P: 619
See string replace at http://www.tutorialspoint.com/python/string_replace.htm Also take a look a the files section in the same tutorial on how to use newlines when writing a file.
Oct 14 '17 #2

P: 8
working solution:

import re
x = open(r'F:\1\xxx.txt')
Lines = x.readlines()


repldict = {'zzz1':(Lines[0]).strip(), 'zzz2':(Lines[1]).strip()}
def replfunc(match):
return repldict[match.group(0)]

regex = re.compile('|'.join(re.escape(x) for x in repldict))
with open(r'F:\1\xxx.txt') as fin, open(r'F:\1\xxx2.txt','w') as fout:
for line in fin:
fout.write(regex.sub(replfunc,line))
Oct 15 '17 #3

Post your reply

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