Python Replace Texts For Each File

A useful function to replace certain texts for each files in a given folder:


Python Replace texts in all Files From a Folder and re-write

import os
# Getting the current work directory (cwd)
thisdir = os.getcwd()

folder = thisdir + '\\path_to_your_folder'

# r=root, d=directories, f = files
for r, d, f in os.walk(folder):
for file in f:
fPath = os.path.join(r, file)

read_lines = []
with open(fPath, 'r') as fp:
read_lines = fp.readlines()
read_lines = [line.rstrip('\n') for line in read_lines]

with open(fPath, 'w') as fw:
for line in read_lines:
newText = line.replace("your text 1 to replace", "replace with").replace('your text 2 to replace', 'repalce with').replace('you got the idea', 'your text to replace with').strip()
if(newText.endswith(')')):
newText = newText + ";"
# do something like append/prepend

if not newText.startswith('--'):
#skip certain lines if you want before writing
fw.write(newText + "\n")

Leave a Reply

Your email address will not be published. Required fields are marked *