python脚本——遍历文件夹和修改文件名

# -*- coding:utf-8 -*-
import os
import os.path
def findTypeFileNotNone(rootdir):
    '''
    1.遍历文件夹中非空的文件  2.修改文件名字  3.统计文件内同行数  4.记录信息到文件中
    :param rootdir: 文件根目录
    :return: 
    '''
    f= open('dirName.txt','w+')
    f.truncate()
    for parent, dirnames, filenames in os.walk(rootdir):  # 三个参数:分别返回1.父目录 2.所有文件夹名字(不含路径) 3.所有文件名字
        print "parent is "+parent
        f.write(">>"+parent+"\n")
        for filename in filenames:
            if ('.txt' in filename):
                if os.path.getsize(os.path.join(parent,filename)):
                    name = '';
                    #文件类型
                    if('001' in filename):
                        name = '新增放款'
                    if('003' in filename):
                        name = '还款计划变更'
                    if('004' in filename):
                        name = '还款申请'
                    #文件行数
                    lines = str(len(open(os.path.join(parent, filename),'r').readlines()))
                    print "file is "+filename+'====='+name+'====='+lines
                    f.write(">>>>>"+filename+"....."+name+'====='+lines+"\n")
            if filename == '20170317.ind':
                os.rename(os.path.join(parent, filename), os.path.join(parent, "20170320.ind"))
    f.close()

if __name__ == '__main__':
    findTypeFileNotNone('C:\\MyDocument\\Test\\v1\\')

你可能感兴趣的:(python脚本——遍历文件夹和修改文件名)