Typora图片打包代码
使用方法:将pack.py放入需要打包的md文件同一目录运行即可。实现效果:pack.pyimport os import re import shutil root_folder = "." target_folder_name = "images" for root, dirs, files in os.walk(root_folder): if target_folder_name in dirs: dirs.remove(target_folder_name) continue for filename in files: if filename.endswith(".md") and filename.lower() != "readme.md": md_path = os.path.join(root, filename) images_folder = os.path.join(os.path.dirname(md_path), target_folder_name) new_folder = os.path.join(root, os.path.splitext(filename)[0]) if not os.path.exists(new_folder): os.makedirs(new_folder) new_md_path = os.path.join(new_folder, filename) shutil.move(md_path, new_md_path) images_subfolder = os.path.join(new_folder, target_folder_name) if not os.path.exists(images_subfolder): os.makedirs(images_subfolder) with open(new_md_path, "r", encoding="utf-8") as f: content = f.read() image_paths = re.findall(r'((.*?))', content) image_paths = [path for path in image_paths if re.match(r'^[a-zA-Z]:\', path)] # 匹配绝对路径 try: for idx, image_path in enumerate(image_paths, start=1): image_name = os.path.basename(image_path) target_path = os.path.join(images_subfolder, f"{idx}_{image_name}") shutil.copy(image_path, target_path) new_image_path = os.path.relpath(target_path, start=os.path.dirname(new_md_path)) content = content.replace(image_path, new_image_path) except Exception as e: print(e) with open(new_md_path, "w", encoding="utf-8") as f: f.write(content) print("完成目录创建、文件移动、图片复制和路径替换")