You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R中按文件夹名称模式批量复制指定图片文件

批量复制图片到对应文件夹的解决方案

方法一:Bash 命令行(适用于 Linux/macOS)

直接在终端执行以下步骤:

  1. 切换到源文件夹目录:
cd ~/PATH/MYFOLDER
  1. 执行循环复制命令:
for dir in LClass_*; do
    target_dir="../${dir#LClass_}"
    cp "$dir"/*.png "$target_dir" 2>/dev/null
    cp "$dir"/*.jpg "$target_dir" 2>/dev/null
done
  • 2>/dev/null 用来忽略“无对应格式文件”的错误提示,避免终端输出冗余信息
  • ${dir#LClass_} 会自动去掉子文件夹名称的LClass_前缀,匹配你创建的目标文件夹

方法二:Python 脚本(跨平台,支持 Windows/Linux/macOS)

如果你更习惯用脚本或者需要跨平台运行,可按以下操作:

  1. 创建一个名为copy_images.py的文件,写入以下代码:
import os
import shutil

# 定义路径(~会自动转换为用户主目录)
source_root = os.path.expanduser("~/PATH/MYFOLDER")
target_root = os.path.expanduser("~/PATH")

# 遍历所有LClass_开头的子文件夹
for dir_name in os.listdir(source_root):
    dir_path = os.path.join(source_root, dir_name)
    # 跳过非文件夹和不符合命名规则的目录
    if not os.path.isdir(dir_path) or not dir_name.startswith("LClass_"):
        continue
    # 提取目标文件夹名称
    target_dir_name = dir_name.replace("LClass_", "")
    target_dir_path = os.path.join(target_root, target_dir_name)
    # 兜底确保目标文件夹存在(即使你已经创建)
    os.makedirs(target_dir_path, exist_ok=True)
    # 复制所有png/jpg文件
    for file_name in os.listdir(dir_path):
        if file_name.lower().endswith((".png", ".jpg")):
            shutil.copy2(os.path.join(dir_path, file_name), target_dir_path)
  1. 在终端运行脚本:
python3 copy_images.py

内容的提问来源于stack exchange,提问作者Wilson Souza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 09:11:54