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

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版本

 1 import os
 2 
 3 
 4 """
 5     与01文件功能的不同,将改名封装成函数
 6 """
 7 
 8 def show_files(path, all_files):
 9     # 首先遍历当前目录所有文件及文件夹
10     file_list = os.listdir(path)
11     # 准备循环判断每个元素是否是文件夹还是文件,是文件的话,把名称传入list,是文件夹的话,递归
12     for file in file_list:
13         # 利用os.path.join()方法取得路径全名,并存入cur_path变量,否则每次只能遍历一层目录
14         cur_path = os.path.join(path, file)
15         # 判断是否是文件夹
16         if os.path.isdir(cur_path):
17             # os.rename(cur_path, cur_path+'asdf')
18             # cur_path = cur_path+'asdf'
19             show_files(cur_path, all_files)
20         else:
21             """
22                 给每个文件重命名
23                 思路:把文件路径用split()函数分割成列表,然后再修改最后的元素
24             """
25             change_file_name(cur_path, 'ssss')
26             all_files.append(file)
27 
28     return all_files
29 
30 
31 def change_file_name(path_name, pre_fix):
32     old_name = path_name.split('\\')
33     print(old_name)
34     os.rename(path_name, '\\'.join(old_name[0:-1]) + '\\' + pre_fix + old_name[-1])
35     return
36 
37 
38 
39 
40 # 传入空的list接收文件名
41 contents = show_files("e:\\python\\hello", [])
42 # 循环打印show_files函数返回的文件名列表
43 for content in contents:
44     print(content)

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

猜你喜欢

转载自www.cnblogs.com/cnapple/p/11793126.html