美文网首页Python学习
批量重命名文件

批量重命名文件

作者: 牵丝笼海 | 来源:发表于2018-07-03 21:28 被阅读3次

    使用Python实现批量重命名文件

    batch_rename_file.py

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    # @Date    : 2018-07-03 16:51:40
    # @Author  : xfwang
    # @email   : xfwangmm@gmail.com
    
    import os
    import sys
    
    def batch_rename_file(path):
        """batch rename all files in the directory"""
        # 获取目录下的所有文件
        file_list = os.listdir(path)
        i = 1
        for file in file_list:
            old_file = os.path.join(path, file) 
    
            # 如果是目录,则跳过
            if os.path.isdir(old_file):
                continue
            # 获取文件名和文件扩展名
            file_name = os.path.splitext(file)[0]
            file_type = os.path.splitext(file)[1]
    
            # 新的文件名
            new_file_name = file_name.replace(file_name, '第' + str(i) + '章')
            i += 1
    
            new_file = os.path.join(path, new_file_name + file_type)
            os.rename(old_file, new_file)
    
            print(old_file + ' -> ' + new_file)
        pass
    
    
    batch_rename_file(sys.argv[1])
    
    # path = r'E:\WorkSpace\HelperUsingPython\test'
    # batch_rename_file(path)
    # input()
    

    命令行执行

    PS E:\WorkSpace> python batch_rename_file.py E:\WorkSpace\test
    

    运行结果

    E:\WorkSpace\test\3d.txt -> E:\WorkSpace\test\第1章.txt
    E:\WorkSpace\test\bb.txt -> E:\WorkSpace\test\第2章.txt
    E:\WorkSpace\test\ds.txt -> E:\WorkSpace\test\第3章.txt
    E:\WorkSpace\test\gd.txt -> E:\WorkSpace\test\第4章.txt
    E:\WorkSpace\test\gg.txt -> E:\WorkSpace\test\第5章.txt
    E:\WorkSpace\test\qw.txt -> E:\WorkSpace\test\第6章.txt
    E:\WorkSpace\test\rt.txt -> E:\WorkSpace\test\第7章.txt
    E:\WorkSpace\test\tt.txt -> E:\WorkSpace\test\第8章.txt
    E:\WorkSpace\test\vv.txt -> E:\WorkSpace\test\第9章.txt
    

    相关文章

      网友评论

        本文标题:批量重命名文件

        本文链接:https://www.haomeiwen.com/subject/rbajuftx.html