markdown自动添加头部信息

# 给content目录下的所有文件添加头部信息

import os
import time

def add_header(file_name):
    datetime = time.strftime("%Y-%m-%dT%H:%M:%S%z", time.localtime())
    with open(file_name, "r+", encoding='utf-8') as f:
        # 文件名去掉路径
        file_name = os.path.basename(file_name)
        # 异常处理,防止文件内容为空
        try:
            content = f.read()
        except UnicodeDecodeError:
            print(file_name + "文件内容为空")
            content = ""
        f.seek(0, 0)
        f.write("---\ndate: " + datetime + "\ntitle: \"" + file_name[:-3] + "\"\n---\n\n" + content)

def delete_header(file_name):
    with open(file_name, 'r+', encoding='utf-8', errors='ignore') as f:
        #删除前5行
        for i in range(5):
            f.readline()
        # 读取剩余内容
        content = f.read()
        f.seek(0, 0)
        f.write(content)

def recursive_add_header(dir_name):
    for file_name in os.listdir(dir_name):
        if file_name.endswith(".md"):
            add_header(os.path.join(dir_name, file_name))
        elif os.path.isdir(os.path.join(dir_name, file_name)):
            recursive_add_header(os.path.join(dir_name, file_name))

def recursive_delete_header(dir_name):
    for file_name in os.listdir(dir_name):
        if file_name.endswith(".md"):
            delete_header(os.path.join(dir_name, file_name))
        elif os.path.isdir(os.path.join(dir_name, file_name)):
            recursive_delete_header(os.path.join(dir_name, file_name))

if __name__ == "__main__":
    recursive_add_header("content")
Published At