Python to replace string in group of files
import os
def replaceText(fileName, oldValue, newValue):
with open(fileName, "r+") as file:
fileText = file.read()
if fileText.find(oldValue) != -1:
print ("Found %r in %s" % (oldValue, fileName))
newFileText = fileText.replace(oldValue, newValue)
file.seek(0)
file.truncate()
file.write(newFileText)
def replaceTextInFiles(dir, extensions, oldValue, newValue):
for dir, subdirs, files in os.walk(dir):
print("dir = %s" % dir)
for file in files:
fileName = os.path.join(dir, file)
print(" file = %s" % fileName)
includeFile = False
for extension in extensions:
if fileName.endswith(extension):
includeFile = True
if includeFile:
print(" file = %s" % fileName)
replaceText(fileName, oldValue, newValue)
else:
print(" (skip %s)" % fileName)
# replaceTextInFiles("c:/mydir", [".ext1", ".ext2", ".ext3"], "old", "new")