Hi Team,
I have written a python function as below. User should pass his input and those input is args for this function and run accordingly. Any help will be much appreciated.
from pathlib import Path
import os, fnmatch
def findReplace(directory, find, replace, filePattern):
# return directory, find, replace, filePattern
for path, dirs, files in os.walk(os.path.abspath(directory)):
for filename in fnmatch.filter(files, filePattern):
filepath = os.path.join(path, filename)
with open(filepath) as f:
s = f.read()
occurances = s.count(find)
if(occurances > 0):
print('There are ' + str(occurances) + ' found for ' +str(find)+ ' under ' +str(directory) + ' in ' + str(files))
# print('There are ' + str(occurances) + ' found for ' +str(find))
s = s.replace(find, replace)
with open(filepath, 'w') as f:
f.write(s)
directory = input('What is the directory name? ')
find = input('What is the pattern you want me to search ? ')
replace = input('What is the pattern you want me to replace with ? ')
filePattern = input('Which files you want me to replace ? ')
findReplace(directory, find, replace, filePattern)