Python脚本--批量修改替换文件名

查看服务器日志的时候,发现某些日志的文件名超级长。通过脚本批量改短一些,方便查看日志(重要日志须先备份,再改名)。

代码:

        

# !/usr/bin/python3
# -*- coding=utf-8 -*-
# @time: 2020-12-09  

import os
import re


file_path = os.getcwd()
fileName_list = os.listdir(file_path)

re_com = re.compile(r"test")


for i in fileName_list:
    oldDir = os.path.join(file_path, i)
    if os.path.isdir(oldDir):
        continue
    fileName_spl = os.path.splitext(i)
    fileName = fileName_spl[0]
    fileType = fileName_spl[1]
    if re_com.search(fileName):
        sub_file = re.sub(re_com, "", fileName)
        newFile = sub_file + fileType
        newDir = os.path.join(file_path, newFile)
        try:
            os.rename(oldDir, newDir)
            print("开始更名   --{}--  更名为  >>{}<<    已完成! ".format(i, newFile))
        except Exception as e:
            print('未知错误---', e)


if __name__ == "__main__":
    pass

posted @   kleinscnb  阅读(12)  评论(0编辑  收藏  举报  
点击右上角即可分享
微信分享提示