Last active
April 8, 2023 21:00
Replace a Markdown section using Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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