954,219 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Search and replace multiple file

Hi Pythonist,

I write the code in Python for search and replace the text in all XML files at current directory.
But I'm unable to find and replace the text "" as empty in all XML files. Here I want to remove the text:
z_{1 - \alpha }^2 \,\sigma _{{\rm SCR}}^2 = \sum\limits_{i = 1}^n {z_{1 - \alpha }^2 \,\sigma _i^2 } + 2\sum\limits_{i \ne }^n {\sum\limits_j^n {z_{1 - \alpha }^2 \,\rho _{ij} \,\sigma _i \,\sigma _j } } ,

as

empty
ie. re.sub(r"(.*)",r"", filePath)
whats wrong with this code and explain how and where to use the script.

And also I want to replace all starting with as and as within the element 1a for all XML files in the current directory.
Here I want to replace the text:
risk modules:1az1-α2 σSCR2=∑i=1nz1-α2 σi2+2∑i≠n∑jnz1-α2 ρij σi σj,z_{1 - \alpha }^2 \,\sigma _{{\rm SCR}}^2 = \sum\limits_{i = 1}^n {z_{1 - \alpha }^2 \,\sigma _i^2 } + 2\sum\limits_{i \ne }^n {\sum\limits_j^n {z_{1 - \alpha }^2 \,\rho _{ij} \,\sigma _i \,\sigma _j } } ,where

as

risk modules:1az1-α2 σSCR2=∑i=1nz1-α2 σi2+2∑i≠n∑jnz1-α2 ρij σi σj,where
Pls. explain how and where to use the script.

Here my main python script is:

import os, sys, shutil

mydir= os.getcwd()
#makedir = os.mkdir('out')
#path = os.getcwd()
#filename = glob.glob(os.path.join(path, '*.xml') )


findreplace = [
('–','–'),
('’','É'),
]

def replaceStringInFile(filePath):
"replaces all findStr by repStr in file filePath"
tempName=filePath+'xml'
# backupName=filePath+'~~'
input = open(filePath)
output = open(tempName,'w')

inF = open(filePath,'r')
s=unicode(inF.read())
inF.close()

for couple in findreplace:
outtext=s.replace(couple[0],couple[1])
s=outtext
outF = open(tempName,'wb')
outF.write(outtext.encode('utf-8'))
outF.close()
# shutil.copy2(filePath,backupName)
# os.remove(filePath)
# os.rename(tempName,filePath)

def myfun(dummy, dirr, filess):
for child in filess:
if '.xml' == os.path.splitext(child)[1] and os.path.isfile(dirr+'/'+child):
replaceStringInFile(dirr+'/'+child)
os.path.walk(mydir, myfun, 3)

Can anyone help me regarding the above 2 points.

Thanks in advance
Naren

narendran_9
Newbie Poster
1 post since Sep 2007
Reputation Points: 10
Solved Threads: 0
 

hi, i have used the method explaned in following link, and this helped me a lot, i am sure that this also ll help you..
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52250

sharma_vivek82
Newbie Poster
19 posts since Mar 2006
Reputation Points: 10
Solved Threads: 0
 

Hi Pythonist,

I write the code in Python for search and replace the text in all XML files at current directory. But I'm unable to find and replace the text "" as empty in all XML files. Here I want to remove the text: z_{1 - \alpha }^2 \,\sigma _{{\rm SCR}}^2 = \sum\limits_{i = 1}^n {z_{1 - \alpha }^2 \,\sigma _i^2 } + 2\sum\limits_{i \ne }^n {\sum\limits_j^n {z_{1 - \alpha }^2 \,\rho _{ij} \,\sigma _i \,\sigma _j } } ,

as

empty ie. re.sub(r"(.*)",r"", filePath) whats wrong with this code and explain how and where to use the script.

And also I want to replace all starting with as and as within the element 1a for all XML files in the current directory. Here I want to replace the text: risk modules:1az1-α2 σSCR2=∑i=1nz1-α2 σi2+2∑i≠n∑jnz1-α2 ρij σi σj,z_{1 - \alpha }^2 \,\sigma _{{\rm SCR}}^2 = \sum\limits_{i = 1}^n {z_{1 - \alpha }^2 \,\sigma _i^2 } + 2\sum\limits_{i \ne }^n {\sum\limits_j^n {z_{1 - \alpha }^2 \,\rho _{ij} \,\sigma _i \,\sigma _j } } ,where

as

risk modules:1az1-α2 σSCR2=∑i=1nz1-α2 σi2+2∑i≠n∑jnz1-α2 ρij σi σj,where Pls. explain how and where to use the script.

Here my main python script is:

import os, sys, shutil

mydir= os.getcwd() #makedir = os.mkdir('out') #path = os.getcwd() #filename = glob.glob(os.path.join(path, '*.xml') )

findreplace = [ ('–','–'), ('’','É'), ]

def replaceStringInFile(filePath): "replaces all findStr by repStr in file filePath" tempName=filePath+'xml' # backupName=filePath+'~~' input = open(filePath) output = open(tempName,'w') inF = open(filePath,'r') s=unicode(inF.read()) inF.close()

for couple in findreplace: outtext=s.replace(couple[0],couple[1]) s=outtext outF = open(tempName,'wb') outF.write(outtext.encode('utf-8')) outF.close() # shutil.copy2(filePath,backupName) # os.remove(filePath) # os.rename(tempName,filePath)

def myfun(dummy, dirr, filess): for child in filess: if '.xml' == os.path.splitext(child)[1] and os.path.isfile(dirr+'/'+child): replaceStringInFile(dirr+'/'+child) os.path.walk(mydir, myfun, 3)

Can anyone help me regarding the above 2 points.

Thanks in advance Naren


Not sure if this will help but you should try this directory compare prog in your problem.

Michael_Smith
Newbie Poster
3 posts since Jan 2009
Reputation Points: 6
Solved Threads: 0
 

This post is over a year old. Just let it die.

Paul Thompson
Veteran Poster
1,119 posts since May 2008
Reputation Points: 264
Solved Threads: 183
 
This post is over a year old. Just let it die.


Ah sorry, I just didn't notice the date. I just fixed the link for a case it is needed to him...Not sure if this will help but you should try this soft for directory compare in your problem.

Michael_Smith
Newbie Poster
3 posts since Jan 2009
Reputation Points: 6
Solved Threads: 0
 

This code will search for the given text in all the files in directories and subdirectories recursively and replace with replace text in given directory:

Save this following peace of code to a search_and_replace_in_multiple_files.py and run.
search_and_replace_in_multiple_files.py "search_string" "replace_string" "c:\\"
it will search in entire c:\ drive all the files and where ever it finds the string it will replace.

#!/usr/bin/env python
# To search and replace a string in multiple files

import sys
import os

if len(sys.argv) < 2:
	print 'usage: %s search_text replace_text directory' \
		% os.path.basename(sys.argv[0])
	sys.exit(0)


stext = sys.argv[1]
rtext = sys.argv[2]
if len(sys.argv) == 4:
	path = os.path.join(sys.argv[3], '*')
else:
	path = '*'


print 'finding: %s and replacing with: %s' % (stext, rtext)
## Traversing through entire directory recursively.
mydir= sys.argv[3]
hole_list=[]
def myfun(s1, s2, s3):
    for file in s3:
		if ".py" in file:
			full_path_file=s2+"\\"+file
			hole_list.append(full_path_file)
os.path.walk(mydir, myfun, '')


for file in hole_list:
	r = open(file, 'r')
	file_content=r.read()
	file_content=file_content.replace(stext,rtext)
	w = open(file, 'w')
	w.write(file_content)

#self.server.osget_path()
seetharama Raju
Newbie Poster
1 post since Oct 2010
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You