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 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
| import os
import shutil
import re
import urllib.parse
def move_images_and_update_links(posts_dir, images_dir):
for root, dirs, files in os.walk(posts_dir):
for file in files:
if file.endswith('.md'):
md_file_path = os.path.join(root, file)
print(f"正在处理文件: {md_file_path}")
if not os.access(md_file_path, os.W_OK):
print(f"没有写权限: {md_file_path}")
continue
with open(md_file_path, 'r', encoding='utf-8') as f:
content = f.read()
new_content = content
image_links = re.findall(r'!\[\[(.*?)\|.*?\]\]', content)
if not image_links:
print(f"未找到图片链接: {md_file_path}")
for image_link in image_links:
image_link = os.path.normpath(image_link)
image_name = os.path.basename(image_link)
source_image_path = os.path.join(root, image_name)
if not os.path.exists(source_image_path):
source_image_path = os.path.join(posts_dir, image_link)
destination_image_path = os.path.join(images_dir, image_name)
print(f"检查图片路径: {source_image_path}")
if os.path.exists(source_image_path):
print(f"正在移动图片: {image_name}")
shutil.move(source_image_path, destination_image_path)
new_link = f'})'
new_content = re.sub(r'!\[\[' + re.escape(image_link) + r'\|.*?\]\]', new_link, new_content)
else:
print(f"图片不存在: {source_image_path}")
if new_content != content:
print(f"文件内容已更改,保存修改: {md_file_path}")
with open(md_file_path, 'w', encoding='utf-8') as f:
f.write(new_content)
else:
print(f"文件内容未变化: {md_file_path}")
posts_dir = './myblog/source/_posts'
images_dir = './myblog/source/images'
move_images_and_update_links(posts_dir, images_dir)
|