【发布时间】:2018-05-18 22:11:39
【问题描述】:
所以我有文件3D_492.png,我试图摆脱所有但最后一个下划线之后的数字。我该怎么办?
我想让3D_492.png变成492.png
更多示例:
Anniversary_1_Purple_710.png变成710.png
它们都在文件夹\Images中
编辑:我很笨,忘了说我想用新名称重命名文件。
谢谢
【问题讨论】:
标签: python string python-3.x filenames
所以我有文件3D_492.png,我试图摆脱所有但最后一个下划线之后的数字。我该怎么办?
我想让3D_492.png变成492.png
更多示例:
Anniversary_1_Purple_710.png变成710.png
它们都在文件夹\Images中
编辑:我很笨,忘了说我想用新名称重命名文件。
谢谢
【问题讨论】:
标签: python string python-3.x filenames
使用拆分:
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))
【讨论】:
str.rpartition 的完美工作:
>>> s = "3D_492.png"
>>> start, sep, end = s.rpartition('_')
>>> end
'492.png'
保证返回三个元素,总和为原始字符串。这意味着您始终可以获得“尾巴”的第二个元素:
>>> '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)
【讨论】:
这是一种方法,使用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']
【讨论】:
听起来您只想拆分 _ 并忽略除最后一个结果之外的所有内容。
*_, result = fname.split("_")
# or:
# result = fname.split("_")[-1]
使用os.rename完成重命名
for fname in fnames: # where fnames is the list of the filenames
*_, new = fname.split("_")
os.rename(fname, new)
请注意,如果您想使用绝对路径执行此操作(例如,如果 fnames 看起来像 ["C:/users/yourname/somefile_to_process_123.png", ...],则需要使用 os.path.split 进行更多处理)
for fpath in fnames:
*dir, basename = os.path.split(fpath)
*_, newname = basename.split("_")
newpath = os.path.join(dir[0], newname)
os.rename(fpath, newpath)
【讨论】:
fname.rsplit('_', 1)[1],因为我相信它会稍微快一些
IndexError 失败)
您可以使用正则表达式来搜索扩展名之前的数字。
import re
def update_name(name):
return re.search(r'\d+\..*', name).group()
update_name('3D_492.png') # '492.png'
【讨论】: