几行 Python 代码实现 Windows 下的文件批量重命名

几行 Python 代码实现 Windows 下的文件批量重命名

一 背景

“C:UsersgyslDocuments数据结构”目录中存在许多文件,现需要对其进行重命名,命名规则为:匹配文件名的前六个字符(这些文件的前六个字符就能区分文件名称,且不重复),源文件及重命名之后的文件的扩展名都是“.mp4”。

二 实现代码

# -*- coding:utf-8 -*-
import os, re, shutil
dst_dir = r'C:\Users\sysl\Documents\数据结构'
file_list = os.listdir(dst_dir)
for file in file_list:
    new_name = re.findall(r'^[数据结构]{4}[0-9]{2}|\.mp4$',file)  # \u4E00-\u9FA5
    if len(new_name) == 2 and file != new_name[0] + new_name[1]:
        shutil.move(os.path.join(dst_dir,file),os.path.join(dst_dir,new_name[0]+new_name[1]))

三 使用备注

3.1 dst_dir 定义了被重命名的目录路径;

3.2 正则表达式可以根据自己需求进行替换,如:

'^.{6}|\.mp4$'
'\u4E00-\u9FA5{4}[0-9]{2}|\.mp4$'

3.3 此脚本 Linux 环境也适用。

上一篇:使用Cloud Application Programming模型开发OData的一个实际例子


下一篇:使用遗传算法解决图着色问题