2025年2月24日 星期一 甲辰(龙)年 腊月廿四 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > Python

Python:遍历文件目录及子目录,并批量改变文件名称

时间:04-20来源:作者:点击数:50

1、0.1版本

  • import os
  • def show_files(path, all_files):
  • # 首先遍历当前目录所有文件及文件夹
  • file_list = os.listdir(path)
  • # 准备循环判断每个元素是否是文件夹还是文件,是文件的话,把名称传入list,是文件夹的话,递归
  • for file in file_list:
  • # 利用os.path.join()方法取得路径全名,并存入cur_path变量,否则每次只能遍历一层目录
  • cur_path = os.path.join(path, file)
  • # 判断是否是文件夹
  • if os.path.isdir(cur_path):
  • # os.rename(cur_path, cur_path+'asdf')
  • # cur_path = cur_path+'asdf'
  • show_files(cur_path, all_files)
  • else:
  • """
  • 给每个文件重命名
  • 思路:把文件路径用split()函数分割成列表,然后再修改最后的元素
  • """
  • name_all = cur_path.split('\\')
  • # print(cur_path)
  • # print(name)
  • os.rename(cur_path, '\\'.join(name_all[0:-1])+'\\asdf'+name_all[-1])
  • all_files.append(file)
  • return all_files
  • # 传入空的list接收文件名
  • contents = show_files("e:\\python\\hello", [])
  • # 循环打印show_files函数返回的文件名列表
  • for content in contents:
  • print(content)

2、0.2版本

  • import os
  • """
  • 与01文件功能的不同,将改名封装成函数
  • """
  • def show_files(path, all_files):
  • # 首先遍历当前目录所有文件及文件夹
  • file_list = os.listdir(path)
  • # 准备循环判断每个元素是否是文件夹还是文件,是文件的话,把名称传入list,是文件夹的话,递归
  • for file in file_list:
  • # 利用os.path.join()方法取得路径全名,并存入cur_path变量,否则每次只能遍历一层目录
  • cur_path = os.path.join(path, file)
  • # 判断是否是文件夹
  • if os.path.isdir(cur_path):
  • # os.rename(cur_path, cur_path+'asdf')
  • # cur_path = cur_path+'asdf'
  • show_files(cur_path, all_files)
  • else:
  • """
  • 给每个文件重命名
  • 思路:把文件路径用split()函数分割成列表,然后再修改最后的元素
  • """
  • change_file_name(cur_path, 'ssss')
  • all_files.append(file)
  • return all_files
  • def change_file_name(path_name, pre_fix):
  • old_name = path_name.split('\\')
  • print(old_name)
  • os.rename(path_name, '\\'.join(old_name[0:-1]) + '\\' + pre_fix + old_name[-1])
  • return
  • # 传入空的list接收文件名
  • contents = show_files("e:\\python\\hello", [])
  • # 循环打印show_files函数返回的文件名列表
  • for content in contents:
  • print(content)

认真写了三个小时,接触python以来花时间学习最长的一次。

晚上再思考了一下,下边的这种方法可能效率更高吧

  • import os
  • """
  • 另一种尝试
  • """
  • def show_files(path, all_files):
  • files = os.listdir(path)
  • # print(files)
  • for file in files:
  • # print(file)
  • if os.path.isdir(path + '/' + file):
  • # print(path + '/' + file)
  • show_files(path + '/' + file, all_files)
  • elif os.path.isfile(path + '/' + file):
  • os.rename(path + '/' + file, path + '/aaa' + file)
  • all_files.append(path + '/aaa' + file)
  • return all_files
  • list_a = []
  • path = "e:/python/hello"
  • contents = show_files(path, list_a)
  • for content in contents:
  • print(content)
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门