Had a similar problem, I needed to change a certain String in every file of a folder if appearing.
Important This is a rather older script, so there are some to do's. I would recommend to resolve those issues as an exercise to improve the code quality:
- Using a try and raise Block if an Error occurs.
- Define regular expressions object instead of defining them in the line, the algorithm works faster with this
- Applying List Comprehensions
Note I use regex101.com for creating my regular expressions.
import os, fnmatch, re
allLinesString = []
def findReplace(directory, 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)
global i
with open(filepath, "r") as f:
for line in f:
# So lets decide here what to do when we go through each line of each file found in the directory
if "String" in line:
# Okay and here we write the String if "String" is in line to an array
allLinesString.append(line)
# And if you want you can even use a regex expression to manipulate the "String" which you just found, or delete certain characters what so ever
# Or write the entry to a varible called num in your case
allLinesString[i] = re.sub(r'^\s', '', allLinesString[i])
# In this case the function searches for all markdown files for the specific string
if __name__ == '__main__':
findReplace("wantedDirectoryPath/", "*.md")