How to Batch Rename Files in Python Using Regex – A Step-by-Step Guide
This article walks through a Python file‑processing challenge, explains the logic behind selective batch renaming using regular expressions, provides a complete script, and demonstrates the solution with clear code and illustrative screenshots for practical automation.
1. Introduction
Hello, I am a Python enthusiast. Recently a member asked how to batch rename files in a directory using Python.
Below is the original problem screenshot:
The following script implements the required functionality:
import os
import re
import time
"""对指定目录下的所有文件进行有选择的修改名称"""
def ReFileName(dirPath, pattern):
"""
:param dirPath: 文件夹路径
:param pattern: 正则匹配模式
:return:
"""
# 对目录下的文件进行遍历
for file in os.listdir(dirPath):
# 判断是否是文件
if os.path.isfile(os.path.join(dirPath, file)):
# 用正则匹配,去掉不需要的词
newName = re.sub(pattern, "", file)
# 设置新文件名
newFilename = file.replace(file, newName)
# 重命名
os.rename(os.path.join(dirPath, file), os.path.join(dirPath, newFilename))
print("文件名已统一修改成功")
if __name__ == '__main__':
timeStart = time.time()
dirPath = r"X:\\文件"
pattern = re.compile(r'\0:-(.+)3')
ReFileName(dirPath, pattern)
timeEnd = time.time()
print("程序运行了%d秒" % (timeEnd - timeStart))2. Solution Process
A community member later suggested an alternative approach, illustrated in the following image:
The provided code successfully resolved the file‑renaming issue.
3. Summary
This article presented a Python file‑processing problem, explained the required logic, and supplied a complete script that batch‑renames files according to a regular‑expression pattern.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
