python如何批量对文件重命名,并另存为其他路径(简单案例)

首先我的photo文件夹下的111文件夹中有5张图片,我想把它们存到222文件夹中,并重命名:


以下是代码:

# coding:utf8
import os

# 图片路径
path='./photo/111'
# 目标文件夹路径
path1='./photo/222'
filelist=os.listdir(path)

j=0

for i in filelist:
    # 判断该路径下的文件是否为图片
    if i.endswith('.jpg'):
        # 打开图片
        src=os.path.join(os.path.abspath(path),i)
        # 重命名
        dst=os.path.join(os.path.abspath(path1),'a'+format(str(j),'0>3s')+'.jpg')
        # 执行操作
        os.rename(src,dst)
        j+=1

运行结果:


  • 10
    点赞
  • 40
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
当然可以!以下是一个示例的Python代码,用于将labelme标注后的图片和JSON文件重命名另存为指定目录: ```python import os import shutil def rename_and_save_files(directory, save_directory): # 遍历指定目录下的文件 for filename in os.listdir(directory): if filename.endswith(".json"): # 查找以.json结尾的文件 json_file = os.path.join(directory, filename) image_file = json_file.replace(".json", ".jpg") # 将.json替换为.jpg if os.path.isfile(image_file): # 检查对应的图片文件是否存在 new_json_name = "new_" + filename new_image_name = "new_" + os.path.basename(image_file) new_json_file = os.path.join(save_directory, new_json_name) new_image_file = os.path.join(save_directory, new_image_name) # 重命名json文件和图片文件另存为指定目录 shutil.copy2(json_file, new_json_file) shutil.copy2(image_file, new_image_file) print(f"重命名并另存为成功:{new_json_file}, {new_image_file}") else: print(f"找不到对应的图片文件:{image_file}") # 指定包含labelme标注文件的目录和另存为目录 directory = "path/to/labelme/files" save_directory = "path/to/save/files" rename_and_save_files(directory, save_directory) ``` 你需要将代码中的`"path/to/labelme/files"`替换为包含标注文件的实际目录路径,将`"path/to/save/files"`替换为你想要另存为的目录路径。运行代码后,它会遍历目录中的所有.json文件,然后查找相应的.jpg文件并将它们重命名为"new_文件名",同时将重命名后的文件另存为指定目录。 希望这可以帮到你!如果有任何问题,请随时问我。
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值