通过python将原本库中的image一次性全部通过image auto upload上传

rt,因为image auto upload只能一个一个文件的上传。如果仓库已经比较大,并且刚开始使用图床,可以尝试将其一次性上传,
可以将所有的图片一次性链接到attachments.md内部,然后上传该文件,但是似乎会和media extended创建的截图相冲突

import os
import glob

# 获取当前目录
current_dir = os.getcwd()


# 获取所有名为attachments的文件夹路径,包括子文件夹中的子文件夹
attachments_dirs = []
for root, dirs, files in os.walk(current_dir):
    for dir in dirs:
        if dir == 'attachments':
            attachments_dirs.append(os.path.join(root, dir))

# 获取所有图片文件路径
image_files = []
for dir in attachments_dirs:
    image_files.extend(glob.glob(os.path.join(dir, '*.jpg')))
    image_files.extend(glob.glob(os.path.join(dir, '*.jpeg')))
    image_files.extend(glob.glob(os.path.join(dir, '*.png')))
    image_files.extend(glob.glob(os.path.join(dir, '*.gif')))
    image_files.extend(glob.glob(os.path.join(dir, '*.bmp')))
    image_files.extend(glob.glob(os.path.join(dir, '*.tiff')))
    image_files.extend(glob.glob(os.path.join(dir, '*.webp')))

# 遍历图片文件,并将文件名和相对路径添加到attachments.md文件中
with open('attachments.md', 'w', encoding='utf-8') as file:
    for image_file in image_files:
        image_filename = os.path.basename(image_file)
        relative_path = os.path.relpath(image_file, current_dir)
        file.write(f'![[{image_filename}]]({relative_path})\n')


然后我们需要修改之前的图片引用

import re
import os

# 定义正则表达式模式
pattern = r'\!\[(.*?)\]\((.*?)\)'

# 以utf-8编码读取attachments.md文件
with open('attachments.md', 'r', encoding='utf-8') as file:
    content = file.read()

# 创建空字典
img_dict = {}

# 使用正则表达式匹配并存储图片信息到字典中
matches = re.findall(pattern, content)
for match in matches:
    img_name = match[0]
    img_link = match[1]
    img_dict[img_name] = img_link

# 定义正则表达式模式
pattern1 = r'\!\[(.*?)\]\((.*?)\.(png|jpg|jpeg|gif|bmp|tiff|webp)\)'
pattern2 = r'\!\[\[(.*?)\.(png|jpg|jpeg|gif|bmp|tiff|webp)\]\]'

# 遍历当前文件夹下的所有Markdown文件,避开attachments.md文件
for root, dirs, files in os.walk('.'):
    for file in files:
        if file.endswith('.md') and file != 'attachments.md':
            # 以utf-8编码读取Markdown文件
            file_path = os.path.join(root, file)
            try:
                with open(file_path, 'r', encoding='utf-8') as f:
                    content = f.read()

                # 使用正则表达式替换图片链接
                content = re.sub(pattern1, lambda match: '![{}]({})'.format(match.group(2), img_dict.get(match.group(2), match.group(0))), content)
                content = re.sub(pattern2, lambda match: '![{}]({})'.format(match.group(1), img_dict.get(match.group(1), match.group(0))), content)

                # 将替换后的内容写回Markdown文件
                with open(file_path, 'w', encoding='utf-8') as f:
                    f.write(content)
            except Exception as e:
                print(f"Error processing file {file_path}: {e}")

这样应该可以了,但是似乎会和media extended创建的截图相冲突

1 个赞