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

  • 2019 年 10 月 4 日
  • 笔记

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

本文链接:https://blog.csdn.net/solaraceboy/article/details/98495695

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

一 背景

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

二 实现代码

# -*- coding:utf-8 -*-  import os, re, shutil  dst_dir = r'C:UserssyslDocuments数据结构'  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]))

扩展:

# -*- coding:utf-8 -*-  import os, re, shutil  dst_dir=r'C:UsersgyslDocumentsC语言'  for file in os.listdir(dst_dir):      shutil.move(os.path.join(dst_dir,file), os.path.join(dst_dir,re.sub('—20考研计算机强化课程C语言','-C语言-强化',file)))

三 使用备注

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

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

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

3.3 此脚本 Linux 环境也适用。