概述
Hi,我是你们的老朋友Eli,最近我在整理我的obsidian上的笔记时,我想将我的笔记内容同步到我的hexo博客文件夹下面出现了问题,原因是在hexo的博客中,front-matter是文件开头YAML代码块,需要将obsidian文件增加对应的属性值(title、categories、index_img、comment等),这一点已经解决——采用obsidian中自带的模板插件就能解决。然而,如何将obsidian笔记内容同步到hexo博客上有很多种方案(很遗憾,没有obsidian同步到hexo到的插件),我采用了一种较为简单的方式——做一个python批处理脚本文件。其优势如下:
- 跨平台好,由于只需要标准库,因此有Python解释器就能在Linux、Windows等操作系统上跑起来。
- 扩展性强,Python代码易维护,模块化程度高,好扩展。
原理
原理很简单,使用了Python的文件操作,将obsidian笔记文件复制一份到目标博客文件夹下。设计一个识别以title开头的内容的方法,循环调用这个方法来替换每一个文件,如果文件不存在,源文件直接复制到目标文件,文件存在则通过title中的内容判断两个文件是否一致,如果一致,执行覆盖原目标文件;如果不一致,跳过目标文件创建一个新目标文件。以下给出了详细代码以及注释。
创建一个名为Sync_ObToHex.py文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| import os import shutil import re
source_dir = r"这里填写你写的笔记内容绝对路径" target_dir = r"这里填写你要同步的文件夹下的内容绝对路径"
os.makedirs(source_dir, exist_ok=True)
os.makedirs(target_dir, exist_ok=True) def extract_title(file_path): """从 Markdown 文件中提取 Front Matter 的 title""" with open(file_path, 'r', encoding='utf-8') as f: content = f.read() match = re.search(r'^title:\s*["\']?(.*?)["\']?\s*$', content, re.MULTILINE) return match.group(1).strip() if match else None for filename in os.listdir(source_dir): source_file = os.path.join(source_dir, filename) target_file = os.path.join(target_dir, filename) if not filename.endswith('.md'): continue if os.path.exists(target_file): source_title = extract_title(source_file) target_title = extract_title(target_file) if source_title == target_title: print(f"[覆盖] 标题相同: {filename} (Title: {source_title})") shutil.copy2(source_file, target_file) else: print(f"[跳过] 标题不同: {filename} (源Title: {source_title}, 目标Title: {target_title})") else: print(f"[新增] {filename}") shutil.copy2(source_file, target_file) print("同步完成!") input("按 Enter 退出...")
|
结果展示

结语
本文采用了半自动方案(Obsidian 插件+Python脚本)实现了本地笔记的同步,效果良好,唯一不足是每次执行脚本都要覆盖已有的内容,造成冗余,期待以后探索出更好的全自动解决方案。