【小试牛刀】使用 Python 批量处理文件,以重命名为例

版权声明:转载请注明来源 https://blog.csdn.net/qq_24598601/article/details/83240387

一、说明

  对经常遇到加有各种后缀的文件名进行批量处理。

二、源码

'''
Created on 2018年10月21日

@author: 欧阳
'''
import os


def BatchReName(path, oldStr, newStr):
    """
    @note: 批量重命名
    @param path: 重名名的文件所在的文件夹
    @param oldStr: 文件名中需要去除的子字符串
    @param newStr: 文件名中去除的子字符串的替换子字符串
    @author: 欧阳  
    """
    
    # 打开文件夹
    dirs = os.listdir(path)
    
    # 输出所有文件和文件夹
    for file in dirs:
        # 获取文件的路径
        filePath = os.path.join(path, file)
        
        # 判断是否是文件夹,是则跳过
        if os.path.isdir(filePath):
            continue
        
        print("文件:" + file + "正在重命名...")
        
        # 对文件名进行分割
        fileSome = os.path.splitext(file)
        oldFileName = fileSome[0]
        fileType = fileSome[1]
        
        # 对文件进行标顺序
        # newFileName = num + "." + oldFileName
        # 新文件名 批量处理文件名中各种统一的后缀
        newFileName = oldFileName.replace(oldStr, newStr)
                
        # 重命名
        src = os.path.join(path, file)
        dst = os.path.join(path, newFileName + fileType)
        os.rename(src, dst)
        
        print("文件:" + file + "重命名为:" + newFileName + fileType)
        
    
if __name__ == '__main__':
    try:
        # 键盘输入文件夹
        path = input("请输入需重名名的文件所在的文件夹:");
        
        # 判断是否是文件夹,不是就需要重新输入
        while(not os.path.isdir(path)):
            # 重新从键盘输入一个文件夹
            path = input("请重新输入文件夹:");
            
        BatchReName(path, "", "")
    except:
        print("输入的文件夹有误!")
 

猜你喜欢

转载自blog.csdn.net/qq_24598601/article/details/83240387