Snippit#
This page reuses BSD 3-Clause License content from TeachBooks (2024). Find out more here.
Snippitall#
This code inserts a code snippet (defined in code line 6) on a specified place for each md file in the directory of your choosing, including all subfolders.
# Snippetall: code for adding code snippet in each md file in a specified directory including all subfolders
import os
# Specify the path to your base folder and line where snippet should be added
directory = 'book/demos'
include_at_line = 1
def insert_code_in_md_files(directory):
# Define the code snippet to insert
code_snippet = """\n<div style="clear: both;">\n\n```{figure} ../../figures/open.png\n---\nwidth: 35%\nalign: right\n```\n\n</div>\n"""
# Walk through all directories and subdirectories
for dirpath, dirnames, filenames in os.walk(directory):
for filename in filenames:
if filename.endswith(".md"): # Check if the file is a Markdown file
file_path = os.path.join(dirpath, filename)
# Read the existing content of the file
with open(file_path, 'r', encoding='utf-8') as file:
lines = file.readlines()
# Insert the code snippet at the specified line
include_at_line = 1
if len(lines) > include_at_line:
lines.insert(include_at_line, code_snippet)
else: # If the file has less than two lines, append the snippet
lines.append(code_snippet)
# Write the modified content back to the file
with open(file_path, 'w', encoding='utf-8') as file:
file.writelines(lines)
print(f"Updated {file_path}")
insert_code_in_md_files(directory)
Snippitonce#
This code inserts a code snippet (defined in code line 6) on a specified place for each md file in the directory of your choosing.
# Snippitonce: code for adding code snippet in specific folder
import os
# Specify the path to your folder
specific_folder = 'book/pedagogy'
include_at_line = 1
def insert_code_in_md_files(specific_folder):
# Define the code snippet to insert
code_snippet = """\n<div style="clear: both;">\n\n```{figure} ../figures/confirmed.png\n---\nwidth: 35%\nalign: right\n```\n\n</div>\n"""
# Iterate over all files in the specified folder
for filename in os.listdir(specific_folder):
if filename.endswith(".md"): # Check if the file is a Markdown file
file_path = os.path.join(specific_folder, filename)
# Read the existing content of the file
with open(file_path, 'r', encoding='utf-8') as file:
lines = file.readlines()
# Insert the code snippet at the second line
if len(lines) > include_at_line:
lines.insert(include_at_line, code_snippet)
else: # If the file has less than two lines, append the snippet
lines.append(code_snippet)
# Write the modified content back to the file
with open(file_path, 'w', encoding='utf-8') as file:
file.writelines(lines)
print(f"Updated {filename}")
insert_code_in_md_files(specific_folder)