Python Forum
search and replace with line in document
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
search and replace with line in document
#1
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?
Reply
#2
For the first question: yes. Instead of
new_str = re.sub('zzz1', (Lines[0]) , string)
you can do
new_str = re.sub('zzz1', Lines[0].strip() , string)
For the second question - what have you tried?
Reply
#3
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))
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Replace for loop to search index position illmattic 5 1,270 Sep-03-2022, 04:04 PM
Last Post: illmattic
  Cloning a directory and using a .CSV file as a reference to search and replace bg25lam 2 2,128 May-31-2021, 07:00 AM
Last Post: bowlofred
  Replace every 20th space with line feed T_Lafferty 3 2,361 Jul-19-2020, 10:37 PM
Last Post: T_Lafferty
  Regex won't replace character with line break Tomf96 2 2,547 Jan-12-2020, 12:14 PM
Last Post: Tomf96
  Replace Line in Textfile Deadline 1 10,366 Nov-04-2019, 07:14 PM
Last Post: Larz60+
  Search for the line number corresponding to a value Lali 0 1,638 Oct-22-2019, 08:56 AM
Last Post: Lali
  How do you replace a word after a match from a list of words in each line of a file? vijju56 1 3,455 Oct-17-2019, 03:04 PM
Last Post: baquerik
  Read each line, replace string and save into a new file igormonteiro 2 3,257 Sep-15-2019, 01:24 PM
Last Post: buran
  Can python be used to search a word document for combinations of 6 digits? gkirt1053 2 2,784 Nov-15-2018, 06:22 PM
Last Post: gkirt1053
  Search & Replace - Newlines Added After Replace dj99 3 3,392 Jul-22-2018, 01:42 PM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020