Python 脚本:批量删除图片文件名中的点和后缀
以下是一个示例程序,可以实现您要求的功能:
import os
# 设置要处理的目录
dir_path = r'D:\imagenet\test'
# 遍历每个子目录
for sub_dir in os.listdir(dir_path):
sub_dir_path = os.path.join(dir_path, sub_dir)
if os.path.isdir(sub_dir_path):
# 遍历子目录下的每个文件
for file_name in os.listdir(sub_dir_path):
file_path = os.path.join(sub_dir_path, file_name)
if os.path.isfile(file_path):
# 去掉文件名中的点及其后面的内容
new_file_name = file_name.split('.')[0]
new_file_path = os.path.join(sub_dir_path, new_file_name)
os.rename(file_path, new_file_path)
上述程序使用 os.listdir() 和 os.path.join() 函数遍历目录和拼接路径,使用 os.path.isfile() 函数判断是否为文件,使用 os.rename() 函数重命名文件。在重命名时,程序将文件名按照点进行分割,取第一个元素作为新的文件名。这样就能去掉文件名中的点及其后面的内容了。
原文地址: https://www.cveoy.top/t/topic/oegl 著作权归作者所有。请勿转载和采集!