Python批量修改文件名模板

源码如下:import os

import re
import sys


filePath = r'F:\BaiduNetdiskDownload\COVID-19CTSeg\3DUNet-Pytorch\label'
fileList = os.listdir(filePath)
# 显示文件
def showFile(filePath):
    fileList = os.listdir(filePath)
    for filename in fileList:
        print(filename)

# 得到当前进程的工作目录
currentpath = os.getcwd()
# 将当前工作目录修改为待修改文件夹的位置
os.chdir(filePath)
print("修改前:/n")
showFile(filePath)
# 名称变量
Patient_num=[1,2,4,5,6,7,8,9,10,11,12,14,15,16,18,19,21,22,23]
# 遍历并修改
# 同时遍历两个变量加zip,否则会报错ValueError: too many values to unpack
for filename,num in zip(fileList,Patient_num): # 匹配文件名正则表达式 pat = ".+\.(nii)" # 进行匹配 pattern = re.findall(pat, filename) os.rename(filename, ('Patient000' + str(num) + '.' + pattern[0])) # 指定重命名之后的文件存放位置 # 回退到程序运行前的工作目录 os.chdir(currentpath) # 刷新 sys.stdin.flush() print("修改后:/n") showFile(filePath)

猜你喜欢

转载自www.cnblogs.com/dyc99/p/12573687.html