前言:
今天抽空把md文件迁移发现大量的文件图片丢失,然后就用到了脚本,但是脚本报错进行修改完善了脚本,成功替换了所有的文件里面的图片链接。
分享一下脚本:针对编写的md文件,单个文件其中的图片可以直接修改路径或者重新编辑图片内容,对于大量的文件中的图片进行修改和修复,单一的修改已经不能满足了。
分享内容:
比如你写的大量的md文件,需要迁移,但是迁移路径可能会变化,于是脚本就派上用场了。(图片中第一个路径是修改前的,第二个路径是修改后的)
脚本代码如下
如果文件中的路径如图1
!(/Users/mac/Downloads/img/1.png)
脚本中修改
modified_content = content.replace("!
(../../../xxx", f"!({new_path}/xxxx")xxx修改成图片中的路径,修改后的如下:content.replace("!(/Users/mac/Downloads/img", f"!({new_path}/img")
指定图片路径就是你迁移后的目录
例如:(你迁移到/Users/mac/但是后缀img没有变化)
# 指定新的图片路径
new_image_path = 'xxxx'可以修改成如下格式
new_image_path = '/Users/mac/'
第二个脚用来把你路径修改后的图片在文件目录下生成一个新的文件夹image,把文件的中的图片放在你文件下,然后把新的图片路径写入md文件中,方便后期查看
脚本帮你把文件优化一下结果如下
脚本完成后的情况
脚本:
1、
import os import chardet def detect_encoding(file_path): with open(file_path, 'rb') as file: rawdata = file.read() result = chardet.detect(rawdata) return result['encoding'] def modify_image_paths(file_path, new_path): try: encoding = detect_encoding(file_path) with open(file_path, 'r', encoding=encoding) as file: content = file.read() # 替换 "../../../xxxxx" md图片的路径 modified_content = content.replace("!(../../../xxx", f"!({new_path}/xxxx") # 替换 "../../../xxxxx" md图片的路径 modified_content = modified_content.replace("!(../../../xxxx", f"!({new_path}/xxxx") with open(file_path, 'w', encoding=encoding) as file: file.write(modified_content) print(f"成功修改文件: {file_path}") except Exception as e: print(f"修改文件时出现错误: {file_path}") print(f"错误信息: {str(e)}") # 指定md文件所在的目录 directory = 'xxxxx' # 指定新的图片路径 new_image_path = 'xxxx' # 遍历目录下的所有md文件 for root, dirs, files in os.walk(directory): for file in files: if file.endswith(".md"): file_path = os.path.join(root, file) modify_image_paths(file_path, new_image_path)
2、
import os import shutil import re def copy_and_update_images(directory): for root, dirs, files in os.walk(directory): for file in files: if file.endswith(".md"): file_path = os.path.join(root, file) with open(file_path, 'r', encoding='utf-8', errors='ignore') as f: content = f.read() if content.startswith('---') and '---' in content[3:]: content = content.split('---', 2)[2].lstrip() images_dir = os.path.join(root, "images") os.makedirs(images_dir, exist_ok=True) image_paths = re.findall(r"!\\((.*?)\)", content) for image_path in image_paths: old_image_path = os.path.join("图片路径自行修改", image_path) if os.path.exists(old_image_path): image_name = os.path.basename(image_path) new_image_path = os.path.join(images_dir, image_name) shutil.copy(old_image_path, new_image_path) content = content.replace(image_path, "images/" + image_name) with open(file_path, 'w', encoding='utf-8') as f: f.write(content) # 指定md文件所在的目录 directory = 'xxxx' copy_and_update_images(directory)
脚本下载:
https://github.com/jiyuhei/md
原文始发于微信公众号(极与黑):Markdown批量修改文件图片
免责声明:文章中涉及的程序(方法)可能带有攻击性,仅供安全研究与教学之用,读者将其信息做其他用途,由读者承担全部法律及连带责任,本站不承担任何法律及连带责任;如有问题可邮件联系(建议使用企业邮箱或有效邮箱,避免邮件被拦截,联系方式见首页),望知悉。
- 左青龙
- 微信扫一扫
-
- 右白虎
- 微信扫一扫
-
评论