Manipulate all .md files at once with python (giant find and replace)

Because the Obsidian to Anki Flashcards Plugin didn’t really work for me and I also used it wrong it created ID’s in all my markdown files (they looked somewhat like this: “<!-- ID: 1234567876543…”). I know that this is only a comment and doesn’t affect the preview but it really bugged me.
So I created a python file that scans through all my folders and subfolders and subsubfolders etc. and replaces the all the strings that begin with <!-- ID: and the next 24 strings.
Essentially it is a python file that scans all folders for .md files and can manipulate them.
It is actually really easy to programm, but I thought I might as well share it.
! BE CAREFULL, try it out on a small folder first, otherwise your whole system will be harmed if something goes wrong. Additionally I would make a backup if you mess around with all your files at once!
Here is the code:

import markdown
import os

def manipulate_md(path):
    with open(path, 'r', encoding="utf8") as f:
        text = f.read()
        startword = "<!--ID: "
        endword = "-->"
    while startword in text:
        if startword in text:
            start= text.rindex(startword)
            text = text.replace(text[start:start + 24], "")
    with open(path, 'w', encoding="utf8") as f:
        f.write(text)

the_path_list = []

def getListOfFiles(dirName):
    # create a list of file and sub directories
    # names in the given directory
    listOfFile = os.listdir(dirName)
    print(listOfFile)
    allFiles = list()
    # Iterate over all the entries
    for entry in listOfFile:
        # Create full path
        fullPath = os.path.join(dirName, entry)
        the_path_list.append(fullPath)
        # If entry is a directory then get the list of files in this directory
        if os.path.isdir(fullPath):
            allFiles = allFiles + [getListOfFiles(fullPath)]
        else:
            allFiles.append(fullPath)

getListOfFiles(Your_Folder_Path) #Add your folder path

print(the_path_list)

for path in the_path_list:
    if ".md" in path:
        manipulate_md(path)
1 Like