Skip to content

Instantly share code, notes, and snippets.

@nmpowell
Last active April 8, 2023 21:00
Show Gist options
  • Save nmpowell/45ac2c2edfc1cc7befafe598eaf5556c to your computer and use it in GitHub Desktop.
Save nmpowell/45ac2c2edfc1cc7befafe598eaf5556c to your computer and use it in GitHub Desktop.
Replace a Markdown section using Python
def replace_markdown_section(
filepath: str, section: str, text: str, pad_before="\n\n", pad_after="\n\n"
) -> None:
"""Replace a section in a markdown file with new text.
Args:
filepath (str): Path to markdown file
section (str): Section header to replace
text (str): Text to replace section with
"""
with open(filepath, "r") as f:
lines = f.readlines()
# Find the start and end of the section
start = 0
end = start
for i, line in enumerate(lines):
if line.startswith(section):
start = i
end = i
continue
if line.startswith("#") and start > 0:
end = i
break
# Replace the section
before = lines[:start]
after = lines[end:]
new_section = section + pad_before + text + pad_after
result = before + [new_section] + after
with open(filepath, "w") as f:
f.writelines(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment