Use Python's split function to slice strings and modify file names in batches

Recently, when training the neural network for target detection, it is found that the brackets in the following file names and the spaces before the brackets need to be removed together.

The storage address of the following pictures is D:\code\new\JPEGImages

Idea: Because the number of digits in front of the picture name is different, and the end of the picture name is (*).jpg, so consider counting down the slice. First cut the file name into two strings through the character ")", then cut the previous string into two strings through "(", and finally add the three strings and replace the original file name.

Example: For example, modify 1_220709 (1).jpg

First divide the character ")" into 1_220709 (1 and .jpg , then divide the previous string into 1_220709 and 1 through "(" , and finally add the three to get 1_2207091.jpg

Specifically look at the code implementation:

import os #导入模块
filepath = 'D:/code/new/JPEGImages' #存放图片的文件夹地址
listnames = os.listdir(filepath)  #读取文件夹里面的文件名,得到一个字符串列表
for index in listnames:  #通过for循环遍历提取listnames容器中的单个文件名
    mid = index.split(')')[0]   #split分割字符串, 分割之后是两个字符串, 索引[0]取前面的字符串
    string3 = index.split(')')[-1]   #索引[-1]取后面的字符串
    string1 = mid.split(' (')[0]   #分割mid中的字符串, 分割之后是两个字符串, 索引[0]取前面的字符串
    string2 = mid.split(' (')[-1]  #分割mid中的字符串, 分割之后是两个字符串, 索引[-1]取后面的字符串
    old_name = filepath + '/' + index #得到老文件名
    new_name = filepath + '/'+ string1 + string2 + string3 #得到新文件名
    os.rename(old_name, new_name) #找到old_name,用new_name将其替换

print('成功!')

After filename modification:

Guess you like

Origin blog.csdn.net/m0_63769180/article/details/129064212