obsidianの全ファイルを1つのmdにまとめるスクリプト
#obsidian #スクリプト
code:python
import os
def merge_obsidian_files(vault_path, output_filename):
"""
指定されたObsidian Vault内の全mdファイルを1つに結合します。
"""
# 出力ファイルのパスを作成
output_path = os.path.join(vault_path, output_filename)
# 既に同名の出力ファイルがある場合は内容をリセット(上書き)
with open(output_path, 'w', encoding='utf-8') as outfile:
outfile.write(f"# All Notes Merged\nGenerated from: {vault_path}\n\n")
count = 0
# ディレクトリを歩き回る(再帰処理)
for root, dirs, files in os.walk(vault_path):
# .obsidian などの隠しフォルダや設定フォルダを除外する
if '.obsidian' in dirs:
dirs.remove('.obsidian')
if '.git' in dirs:
dirs.remove('.git')
for file in files:
# Markdownファイルのみを対象とし、出力ファイル自身は読み込まないようにする
if file.endswith(".md") and file != output_filename:
file_path = os.path.join(root, file)
try:
with open(file_path, 'r', encoding='utf-8') as infile:
content = infile.read()
# 出力ファイルに書き込み(追記モード)
with open(output_path, 'a', encoding='utf-8') as outfile:
# 区切りとしてファイル名をH1見出しで挿入
# 相対パスを表示したい場合は file ではなく os.path.relpath(file_path, vault_path) を使用
outfile.write(f"\n\n---\n\n") # 水平線
outfile.write(f"# {file.replace('.md', '')}\n\n") # タイトル
outfile.write(content)
count += 1
print(f"Merged: {file}")
except Exception as e:
print(f"Error reading {file}: {e}")
print(f"\n完了しました! 合計 {count} 個のファイルを結合しました。")
print(f"出力ファイル: {output_path}")
# ==========================================
# 設定エリア:ここを自分の環境に合わせて書き換えてください
# ==========================================
# 1. ObsidianのVault(保管庫)のフォルダパス
# Windowsの例: r"C:\Users\Name\Documents\MyVault"
# Mac/Linuxの例: "/Users/Name/Documents/MyVault"
TARGET_VAULT_PATH = r"/Path/To/Your/ObsidianVault"
# 2. 出力するファイル名
OUTPUT_FILE_NAME = "all_notes_merged.md"
# 実行
if __name__ == "__main__":
if os.path.exists(TARGET_VAULT_PATH):
merge_obsidian_files(TARGET_VAULT_PATH, OUTPUT_FILE_NAME)
else:
print("指定されたパスが見つかりません。パスを確認してください。")