将指定文件夹中的图片文件复制到另一个文件夹,并按照自然数递增的命名规则重命名的程序

本文介绍了一个Python程序,它遍历`photos`文件夹及其子文件夹中的图片文件,将它们移动到`photos_new`文件夹,并保持原有文件结构,同时重命名文件以数字序号标识。
摘要由CSDN通过智能技术生成

 文件目录结构

C:.
├─data
│  ├─photos
│  │  ├─1
│  │  ├─2
│  │  ├─3
│  │  ├─4
│  │  ├─5
│  │  ├─6
│  │  ├─7
│  │  └─8
│  └─photos_new
│      ├─1
│      ├─2
│      ├─3
│      ├─4
│      ├─5
│      ├─6
│      ├─7
│      └─8
└─try.py

代码 

import os
import shutil
from tqdm import tqdm

# 获取当前脚本所在目录
current_directory = os.path.dirname(os.path.abspath(__file__))

# 指定原始photos文件夹的路径
photos_directory = os.path.join(current_directory, 'photos')

# 指定新的photos文件夹的路径
new_photos_directory = os.path.join(current_directory, 'photos_new')

# 创建新的photos文件夹
if not os.path.exists(new_photos_directory):
    os.makedirs(new_photos_directory)

# 初始化文件名计数器
file_counter = 1

# 遍历原始photos文件夹下的所有子文件夹
for folder_name in os.listdir(photos_directory):
    folder_path = os.path.join(photos_directory, folder_name)
    
    # 检查子文件夹是否存在
    if os.path.isdir(folder_path):
        # 创建新的子文件夹
        new_folder_path = os.path.join(new_photos_directory, folder_name)
        if not os.path.exists(new_folder_path):
            os.makedirs(new_folder_path)
        
        # 遍历子文件夹中的所有文件
        files = os.listdir(folder_path)
        files.sort()  # 对文件列表按字母顺序排序
        
        for file_name in tqdm(files, desc=folder_name):
            file_path = os.path.join(folder_path, file_name)
            
            # 检查文件是否为图片文件
            if os.path.isfile(file_path) and file_name.lower().endswith(('.jpg', '.jpeg', '.png')):
                # 构建新的文件名
                file_extension = os.path.splitext(file_name)[1].lower()
                new_file_name = str(file_counter) + file_extension
                new_file_path = os.path.join(new_folder_path, new_file_name)
                
                # 复制文件到新的文件夹并重命名
                shutil.copy(file_path, new_file_path)
                
                # 增加文件名计数器
                file_counter += 1

  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值