把md文件和图片资源从gridea迁移到hexo

• 4 分钟阅读 • python

gridea用了半年,开始试试hexo。这是一个迁移脚本。

这是deepseek完成的作业。

hexo是一个快速、简洁且高效的博客框架。

gridea是一个自带客户端的博客框架。

完整脚本

import os
import shutil

def sync_files(src_dir, dst_dir):
    """同步源目录到目标目录(增量模式)"""
    if not os.path.isdir(src_dir):
        print(f"错误:源目录不存在 {src_dir}")
        return False
    
    if not os.path.exists(dst_dir):
        print(f"创建目标目录 {dst_dir}")
        os.makedirs(dst_dir)

    print(f"正在同步 {src_dir} -> {dst_dir}")
    
    total = copied = skipped = 0
    
    for root, _, files in os.walk(src_dir):
        for filename in files:
            total += 1
            src_path = os.path.join(root, filename)
            rel_path = os.path.relpath(src_path, src_dir)
            dst_path = os.path.join(dst_dir, rel_path)
            
            # 检查是否需要复制
            if not os.path.exists(dst_path):
                copy_reason = "新文件"
            else:
                # 比较修改时间和文件大小
                src_stat = os.stat(src_path)
                dst_stat = os.stat(dst_path)
                
                if src_stat.st_mtime > dst_stat.st_mtime or src_stat.st_size != dst_stat.st_size:
                    copy_reason = "已更新"
                else:
                    skipped += 1
                    continue
            
            # 确保目标目录存在
            os.makedirs(os.path.dirname(dst_path), exist_ok=True)
            
            # 执行复制
            try:
                shutil.copy2(src_path, dst_path)
                print(f"已复制 ({copy_reason}): {rel_path}")
                copied += 1
            except Exception as e:
                print(f"复制失败 {rel_path}: {str(e)}")
    
    print(f"同步完成. 总计: {total}, 已复制: {copied}, 已跳过: {skipped}")
    return True

def main():
    # 同步图片目录
    sync_files(
        r"E:\documents\Gridea\post-images",
        r"D:\hexo\blog\source\post-images"
    )
    
    # 同步文章目录
    sync_files(
        r"E:\documents\Gridea\posts",
        r"D:\hexo\blog\source\_posts"
    )

if __name__ == "__main__":
    main()

保存为 sync_hexo.py,直接运行。

特点:

注意事项

确保源目录路径正确(特别是Gridea的默认路径可能有变化)。

就是任性,用gridea客户端写,用hexo生成网站。

文章标签: python

上一篇 : 抓取豆瓣书影音信息
下一篇 : 从 docker 容器生成 docker-compose yaml 定义
留言
阅读进度 0%