Created
May 9, 2020 19:32
-
-
Save grandams/4f3ef0c9cdce2d048b8bea391e91b953 to your computer and use it in GitHub Desktop.
Thanks for sharing, it helped me quite a bit! Using your script I encountered 2 issues, though.
- If there are empty markdown files (actually, if there are no lines that contain
"# "
), the while loop inextract_title_md
turns to an infinite loop. Got it working with this hacky fix:
def extract_title_md(md_file):
""" Return the first level 1 md title (without # and trailing newline) """
lines = (line for line in open(md_file, "r"))
try:
line = next(lines) # prime generator
except StopIteration:
# file is empty
return md_file.split("/")[-1].split(".md")[0] # return plain filename
while "# " not in line:
try:
line = next(lines)
except StopIteration:
# file doesn't contain title
return md_file.split("/")[-1].split(".md")[0] # return plain filename
return line.lstrip('# ').rstrip('\n')
- The built-in string methods
str.lstrip
andstr.rstrip
have some odd behaviour, if you actually give them a substring. From the Docstring:Signature: str.rstrip(self, chars=None, /) [...] If chars is given and not None, remove characters in chars instead.
So that means, that not only leading or trailing characters are removed, but all characters ofchars
that are found instr
. This lead to a weird behaviour in e.g. line 128, where I exchanged thenav_path=prettify(true_path.lstrip(root_doc_dir + "/"))
with anav_path=prettify(true_path.replace(root_doc_dir + "/", ""))
. Not the best, but probably the quickest fix. :-)
Anyway, thanks again for sharing, hope this helps.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I am trying to do the same, will this script help me to add any md files dynamically to mkdocs.yml