批量修改文件中的markdown图片格式
import os
import re
def replace_image_format(directory):
# 定义目标格式的正则表达式(包含"media/Images"的情况)
# “[[media/Images/filename.png]]
pattern_with_path = r'!\[\[media/Images/([^\]]+)\]\]'
# 定义目标格式的正则表达式(不包含"media/Images"的情况)
# “[[filename.png]]
pattern_without_path = r'!\[\[([^\]]+)\]\]'
# 遍历目录下的所有文件
for root, _, files in os.walk(directory):
for file in files:
if file.endswith(".md"):
filepath = os.path.join(root, file)
# 读取文件内容
with open(filepath, 'r') as f:
content = f.read()
# 使用正则表达式查找目标格式并替换为新格式
if 'media/Images' in content:
new_content = re.sub(pattern_with_path, r'', content)
else:
new_content = re.sub(pattern_without_path, r'', content)
# 处理文件名中的宽度内容(如果有)“[[filename.png]]”
new_content = re.sub(r'\|\d+', '', new_content)
# 写入修改后的内容到文件
with open(filepath, 'w') as f:
f.write(new_content)
if __name__ == "__main__":
# 指定目录,替换该目录下所有md文件中的格式
target_directory = "/md_path"
replace_image_format(target_directory)ChatGPT解析
for root, _, files in os.walk(directory):解释
for root, _, files in os.walk(directory):解释最后更新于