Modify all file names in a folder in batches

Just look at the code directly, modify the folder and modify the content and run it directly.

'''
  CreateTime :  2023/4/11 15:17
  ModifyTime :  2023/4/11 15:17
  Author     :  Teng Shang
  File       :  Modify_File_Name.py
  IDE        :  PyCharm 
'''
# 批量修改文件名
# 批量修改图片文件名
import os
import re
import sys


def re_name_all():
    file_path = r""
    file_list = os.listdir(file_path)  # 待修改文件夹
    print("修改前:" + str(file_list))  # 输出文件夹中包含的文件
    current_path = os.getcwd()  # 得到进程当前工作目录
    os.chdir(file_path)  # 将当前工作目录修改为待修改文件夹的位置
    # num = 1  # 名称变量
    for fileName in file_list:  # 遍历文件夹中所有文件
        pat = ".+\.(jpg|png|gif|py|txt)"  # 匹配文件名正则表达式
        pattern = re.findall(pat, fileName)  # 进行匹配
        file_name_new = fileName.replace("test", "train")
        os.rename(fileName, file_name_new)  # 文件重新命名
        # num = num + 1  # 改变编号,继续下一项
    print("---------------------------------------------------")
    os.chdir(current_path)  # 改回程序运行前的工作目录
    sys.stdin.flush()  # 刷新
    print("修改后:" + str(os.listdir(file_path)))  # 输出修改后文件夹中包含的文件


if __name__ == '__main__':
    re_name_all()

Guess you like

Origin blog.csdn.net/weixin_52127098/article/details/130726194