filename = "3D_710.png"
# create a list of the parts of the file name separated by "_"
filename_parts = filename.split("_")
# new_file is only the last part
new_file = filename_parts[-1]
print new_file
# 710.png
完整示例包括重命名,假设Images与包含Python脚本的目录相关:
from os import listdir, rename
from os.path import isfile, join, realpath, dirname
dir_path = dirname(realpath(__file__))
images_path = join(dir_path, "Images")
only_files = [f for f in listdir(images_path) if isfile(join(images_path, f))]
for file in only_files:
filename_parts = file.split("_")
# new_file is only the last part
new_file = filename_parts[-1]
rename(join(images_path, file), join(images_path, new_file))
import os
lst = ['3D_492.png', 'Anniversary_1_Purple_710.png']
res = [os.path.basename(i).split('_')[-1] for i in lst]
print(res)
['492.png', '710.png']
import os
os.chdir('\Images')
for old_name in os.listdir('.'):
new_name = old_name.rpartition('_')[2]
if not exists(new_name):
os.rename(old_name, new_name)
使用拆分:
完整示例包括重命名,假设
Images
与包含Python脚本的目录相关:这里有一种方法,使用
os.path.basename
然后str.split
提取最后一个下划线后面的字符:非常适合^{} :
它保证返回三个元素,这三个元素和原始字符串相加。这意味着您始终可以获得“tail”的第二个元素:
拼凑起来:
相关问题 更多 >
编程相关推荐