脚本作用:对markdown文件中引用的所有图片进行位置整理。
# 将 md 文件中引用的图片移动到 md 文件所在文件夹下的 [.文件名] 的文件夹下,并修改 md 文件中的图片引用为相对路径
from pathlib import Path
import re
import shutil
def findAllFile(top_dir, tem):
for p in Path(top_dir).rglob("*" + tem):
yield str(p)
def pre_main(img_type):
# 先查找所有md文档里的图片文件名,然后在所有文件中查找该文件
# 找到后移动到md文档所在的文件夹下的 [.文件名] 的文件夹里,并修改md文档中的图片引用为相对路径
# 找不到图片,打印文件名和图片名
project_dir = "C:/Users/Wu/Desktop/Notes"
# project_dir = r"C:\Users\Wu\Desktop\Notes\zz_tem_test" # 测试文件夹
for md_file_path in findAllFile(project_dir, ".md"): # 查找所有md文档
md_file_path = Path(md_file_path)
md_name = md_file_path.stem # md_name = "xxx"
f1 = open(md_file_path, "r", encoding="utf8")
lines = f1.readlines()
f1.close()
f2 = open(md_file_path, "w", encoding="utf8")
for s in lines:
try:
# 先查找md文档里的是否存在引用图片
if img_type == ".png":
# 匹配引用图片语句,包括前面的中括号和感叹号
patt_ref = r"!\[(.*?)\]\((.*?\.png)\)" # 匹配示例 
patt_file = r"\((.*?\.png)\)" # 匹配示例 (xxx/xxx.png)
elif img_type == ".jpg":
patt_ref = r"!\[(.*?)\]\((.*?\.jpg)\)" # 匹配示例 
patt_file = r"\((.*?\.jpg)\)"
else:
raise Exception("图片类型错误")
s_new = s # 如果文件中没有引用图片,那么保持文件原内容不变
pattern_ref = re.compile(patt_ref)
pattern_file = re.compile(patt_file)
result_ref = pattern_ref.search(s)
if result_ref is not None:
# ========================修改图片引用为相对路径
ref_sentence = result_ref.group(0)
file_path_ori = pattern_file.search(ref_sentence).group(0)[1:-1]
file_name_with_suffix = file_path_ori.split("/")[-1] # 只取文件名
# ========================在 md 文件所在文件夹下遍历图片,找到引用的图片,并移动到新文件夹
found = False
md_file_dir = md_file_path.parent
for ori_img_path in md_file_dir.rglob("*" + img_type):
if file_name_with_suffix in str(ori_img_path) and not found:
found = True
dest_dir = md_file_dir / ("." + md_name)
dest_dir.mkdir(exist_ok=True) # 创建文件夹
# 移动图片到新文件夹
dest_img_path = dest_dir / file_name_with_suffix
# 如果路径不同则进行移动
if str(ori_img_path) != str(dest_img_path):
shutil.move(ori_img_path, dest_img_path)
print(md_file_path)
print(str(ori_img_path), "---->", str(dest_img_path))
# 替换引用字符串
s_new = re.sub(pattern_ref, "", s)
if not found:
print(md_file_path)
print(s + "---->图片未找到")
elif s_new != s:
# 判断文件是否被修改过
print(md_file_path)
print(s + "---->" + s_new)
f2.write(s_new)
except Exception as e:
# 防止发生错误导致文件内容丢失
print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", e)
print(md_file_path)
f2.write(s)
f2.close() # 关闭文件
if __name__ == "__main__":
ATTACH_IMG_TYPE = [".png", ".jpg"]
for img_type in ATTACH_IMG_TYPE:
pre_main(img_type)
TODO 图片名不能有重复的