Python遍历多层文件夹重命名文件

前言

  • 本文是个人使用Python遍历多层文件夹重命名文件的电子笔记,由于水平有限,难免出现错漏,敬请批评改正。
  • 更多精彩内容,可点击进入我的个人主页查看

前提条件

相关介绍

  • Python是一种跨平台的计算机程序设计语言。是一个高层次的结合了解释性、编译性、互动性和面向对象的脚本语言。最初被设计用于编写自动化脚本(shell),随着版本的不断更新和语言新功能的添加,越多被用于独立的、大型项目的开发。
  • Python OS模块是负责程序与操作系统的交互,提供了访问操作系统底层的接口和非常丰富的方法用来处理文件和目录。

实验环境

  • Python 3.x (面向对象的高级语言)

Python遍历多层文件夹重命名文件

├─1
│  ├─1
│  │      Image-0000.bmp
│  │      Image-0001.bmp
│  │
│  └─2
│         Image-0000.bmp
│         Image-0001.bmp
│
├─2
│  ├─1
│  │      Image-0000.bmp
│  │      Image-0001.bmp
│  │
│  └─2
│         Image-0000.bmp
│         Image-0001.bmp
│
└─3
   ├─1
   │      Image-0000.bmp
   │      Image-0001.bmp
   │
   └─2
          Image-0000.bmp
          Image-0001.bmp

代码实现

import os

def renames(src_path):
    filenames = os.listdir(src_path)
    # print(filenames)
    src_path_split = src_path.split('\\')
    # print(src_path_split)
    for filename in filenames:
        old_name = os.path.join(src_path,filename)
        change_name = src_path_split[0]+'_'+src_path_split[1]+'_'+filename
        new_name = os.path.join(src_path,change_name)
        # print(old_name)
        # print(change_name)
        # print(new_name)
        os.rename(old_name, new_name)

if __name__=="__main__":
    first_dirlist = os.listdir()
    first_dirlist = [i for i in first_dirlist if not i.endswith('.py')]  # ???????????
    # print(first_dirlist)
    for dir1 in first_dirlist: # ???????????
        second_dirlist = os.listdir(dir1) # ???????????
        # print(second_dirlist)
        for dir2 in second_dirlist: # ???????????
            src_path = os.path.join(dir1,dir2) # ??????
            # print(src_path)
            renames(src_path) 

输出结果

├─1
│  ├─1
│  │      1_1_Image-0000.bmp
│  │      1_1_Image-0001.bmp
│  │
│  └─2
│         1_2_Image-0000.bmp
│         1_2_Image-0001.bmp
│
├─2
│  ├─1
│  │      2_1_Image-0000.bmp
│  │      2_1_Image-0001.bmp
│  │
│  └─2
│         2_2_Image-0000.bmp
│         2_2_Image-0001.bmp
│
└─3
   ├─1
   │      3_1_Image-0000.bmp
   │      3_1_Image-0001.bmp
   │
   └─2
          3_2_Image-0000.bmp
          3_2_Image-0001.bmp

更多精彩内容,可点击进入Python日常小操作专栏或我的个人主页查看

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

FriendshipT

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值