将一个文件夹内的所有文件的文件名改为按数字顺序排列

将文件夹下的所有文件改名为按顺序命名的文件可以在我们编写程序时降低编程难度

第一种方法

import os
import shutil

# 设置源文件夹路径
source_folder = r"C:\Users\user\Desktop\1"
# 设置目标文件夹路径
destination_folder = r"C:\Users\user\Desktop\2"

# 如果目标文件夹不存在,则创建它
if not os.path.exists(destination_folder):
    os.makedirs(destination_folder)

# 获取源文件夹中所有文件列表
files = os.listdir(source_folder)

# 设置文件开始的数字
counter = 1

# 遍历源文件夹中的文件
for file_name in files:
    # 检查文件是否以 ".jpg" 结尾,可以修改为其他后缀
    if file_name.endswith(".jpg"):
        # 生成新文件名
        new_file_name = str(counter) + ".jpg"
        # 构建源文件路径
        source_file_path = os.path.join(source_folder, file_name)
        # 构建目标文件路径
        destination_file_path = os.path.join(destination_folder, new_file_name)
        # 复制图片文件
        shutil.copy(source_file_path, destination_file_path)
        # 计数器加一
        counter += 1

print("文件复制完成!")

第二种方法

import os
import shutil


def rename_and_copy_images(source_folder, target_folder):
    # 获取源文件夹中的所有文件,并获取文件的完整路径
    files = [os.path.join(source_folder, f) for f in os.listdir(source_folder)]
    # 仅保留图片文件(假设图片格式为jpg, png, jpeg)
    image_files = [f for f in files if f.lower().endswith(('.jpg', '.jpeg', '.png'))]
    # 按文件创建时间排序
    image_files.sort(key=lambda x: os.path.getctime(x))

    # 确保目标文件夹存在
    if not os.path.exists(target_folder):
        os.makedirs(target_folder)

    # 遍历并重命名、复制文件
    for idx, image_file in enumerate(image_files):
        new_name = f"{idx + 1}{os.path.splitext(image_file)[1]}"  # 保留原文件扩展名
        target_path = os.path.join(target_folder, new_name)
        shutil.copy2(image_file, target_path)

    print("所有图片已重命名并复制到目标文件夹。")


# 使用示例
source_folder = r'C:\Users\user\Desktop\1'
target_folder = r"C:\Users\user\Desktop\2"
rename_and_copy_images(source_folder, target_folder)

更改前
在这里插入图片描述
更改后
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值