Halo博客两年崩了两三次,受不了了,干脆换到halo了,写了个脚本生成front matter

Python 程序

import os
import datetime
import re

def add_front_matter(folder_path):
    # 获取文件夹名称作为categories
    folder_name = os.path.basename(folder_path)
    
    # 遍历文件夹下的所有文件
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            # 确保文件为Markdown格式
            if file.endswith(".md"):
                file_path = os.path.join(root, file)
                
                # 读取文件内容
                with open(file_path, 'rb') as f:
                    content = f.read().decode('utf-8')
                
                # 检查是否已存在front matter
                if re.match(r'^---[\s\S]*?---', content, re.MULTILINE):
                    print(f"Front matter already exists in {file_path}. Skipping...")
                    continue
                
                # 提取文件名中下划线前的字符串作为title
                title = os.path.splitext(file)[0].split('-')[0]
                
                # 构建front matter
                front_matter = f"""---
title: {title}
date: "{datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')}"
categories:
  - {folder_name}
---
"""
                # 将front matter添加到文件开头
                with open(file_path, 'w',encoding='utf-8') as f:
                    f.write(front_matter + content)
                
                print(f"Front matter added to {file_path}.")

# 指定文件夹路径
folder_path = "./数据结构"

# 执行添加front matter操作
add_front_matter(folder_path)