以下是使用 Python 脚本批量去除文件夹内文件名后缀的代码示例:

import os

# 指定目录路径
path = r'D:\imagenet\test'

# 遍历目录下的每个文件夹
for foldername in os.listdir(path):
    folderpath = os.path.join(path, foldername)
    if os.path.isdir(folderpath):
        # 遍历文件夹下的每个文件
        for filename in os.listdir(folderpath):
            filepath = os.path.join(folderpath, filename)
            if os.path.isfile(filepath):
                # 去掉文件名的后缀
                newfilename = os.path.splitext(filename)[0]
                newfilepath = os.path.join(folderpath, newfilename)
                os.rename(filepath, newfilepath)
                print(f'重命名 {filename} 为 {newfilename}')

该脚本使用 os 模块访问文件系统,包括列出目录下的文件和文件夹,以及重命名文件。首先指定需要操作的目录路径,然后使用 os.listdir() 函数遍历目录下的每个文件夹。对于每个文件夹,程序使用 os.listdir() 函数再次遍历其中的每个文件,如果文件存在且不是文件夹,则使用 os.path.splitext() 函数去掉文件的后缀,并使用 os.rename() 函数重命名文件。最后,程序会输出每个文件的重命名操作。

Python 脚本: 批量去除文件夹内文件名后缀

原文地址: https://www.cveoy.top/t/topic/oegA 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录