除去文件名中的数字以外的所有内容

2024-06-26 12:51:01 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有一个文件3D_492.png,我试图去掉所有的东西,但是最后一个下划线后面的数字。我该怎么办?你知道吗

我想3D_492.png变成492.png

更多示例: Anniversary_1_Purple_710.png变成710.png

它们都在\Images文件夹中

编辑:我很笨,忘了说我想用新名字重命名文件。

谢谢


Tags: 文件文件夹编辑示例png数字名字重命名
3条回答

使用拆分:

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))

这里有一种方法,使用os.path.basename然后str.split提取最后一个下划线后面的字符:

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']

非常适合^{}

>>> s = "3D_492.png"
>>> start, sep, end = s.rpartition('_')
>>> end
'492.png'

它保证返回三个元素,这三个元素和原始字符串相加。这意味着您始终可以获得“tail”的第二个元素:

>>> 'Anniversary_1_Purple_710.png'.rpartition('_')[2]
'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)

相关问题 更多 >