Pthon循环所有文件夹(含子文件夹),找到指定格式文件,修改其后缀名

  废话不多说,直接撸代码:

#!/usr/bin/python 
# -*- coding: utf-8 -*-
# 遍历所有文件夹,修改指定格式文件后缀名
import os

filter=[".cs"] #设置过滤后的文件类型 当然可以设置多个类型

def all_path(dirname):

    #result = []#所有的文件

    for maindir, subdir, file_name_list in os.walk(dirname):

        # print(maindir) #当前主目录
        # print(subdir) #当前主目录下的所有目录
        # print(file_name_list)  #当前主目录下的所有文件

        for filename in file_name_list:
            apath = os.path.join(maindir, filename)#合并成一个完整路径
            portion = os.path.splitext(apath)
            ext = portion[1]  # 获取文件后缀 [0]获取的是除了文件名以外的内容
            if ext in filter:
                newname = portion[0] + ".cs"
                os.rename(apath, newname)#修改

    #return result

print(all_path("F:TEMP"))
原文地址:https://www.cnblogs.com/wanggang2016/p/10854067.html