Skip to content

Instantly share code, notes, and snippets.

@nnja
Created October 17, 2020 20:44
Show Gist options
  • Save nnja/3dc4c92b9a864b2242c3fae5be361f1f to your computer and use it in GitHub Desktop.
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
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