欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

批量重命名文件

程序员文章站 2022-07-02 20:30:35
...

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

batch_rename_file.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2018-07-03 16:51:40
# @Author  : xfwang
# @email   : [email protected]

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.jianshu.com/p/4e2f3c4b6632