Created
October 17, 2020 20:44
-
-
Save nnja/3dc4c92b9a864b2242c3fae5be361f1f to your computer and use it in GitHub Desktop.
Python script to rename hugo chapters as standalone content pages and remove auto-generated content
This file contains 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
import os | |
lines_to_remove = { | |
'pre = "<b>X. </b>"\n', | |
'chapter = true\n', | |
'### Chapter X\n', | |
'# Some Chapter title\n', | |
'Lorem Ipsum.', | |
} | |
# find all sub-directories | |
directories = next(os.walk('.'))[1] | |
for directory in directories: | |
# the subdirectory contains a chapter_name/_index.md file | |
chapter_index = f"{directory}/_index.md" | |
if os.path.exists(chapter_index): | |
# rename it to chapter_name.md instead | |
page_name = f"{directory}.md" | |
os.rename(chapter_index, page_name) | |
print(f"renamed chapter to: {page_name}") | |
# remove the unneeded auto-generated chapter content | |
with open(page_name,"r+") as f: | |
new_f = f.readlines() | |
f.seek(0) | |
for line in new_f: | |
if line not in lines_to_remove: | |
f.write(line) | |
f.truncate() | |
# clean up the now empty directories | |
for directory in directories: | |
if os.listdir(directory): | |
print("Something went wrong. directory is not empty!") | |
os.sys.exit(1) | |
os.rmdir(directory) | |
print("Done!") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment