python小工具-重命名文件

104 阅读1分钟

重命名文件夹下的文件是我们工作中经常需要用到的,python做这种脚本批处理工作非常优秀,下面我们直接看代码:

#encoding: utf-8
import os
def wrfilename(dir):
    files2 = os.listdir(dir)
    print('tempfiles==',files2)
    # print('path==',os.path)
    for filename in files2:
        portion = os.path.splitext(filename)
        print('portion==',portion)
        if os.path.isdir(filename):
            subpath = os.getcwd()+'/'+filename
            os.chdir(subpath)
            wrfilename(subpath)
        elif portion[1] != '.txt' and portion[1] != '.py':
             newname = filename + '.txt'
             os.rename(dir+'/'+filename, dir+'/'+newname)

# wrfilename('.')

def rename():
    for root,dirs,files in os.walk('.',topdown=False):
        for name in files:
            path = os.path.join(root, name)
            print('path==', path)
            portion = os.path.splitext(name)
            if portion[1] != '.txt' and portion[1] != '.py':
                os.rename(path, path + '.txt')

rename()