Share

遍历目录并替换每个子目录中名为1.mp3的文件为其上一级目录的名称

import os

def rename_mp3_files(base_dir):
    for root, dirs, files in os.walk(base_dir):
        for file in files:
            if file == '111 (1).wav':
                # 获取上一级目录的名称
                parent_dir = os.path.basename(os.path.abspath(os.path.join(root, os.pardir)))
                
                # 构造新的文件名
                new_filename = os.path.join(root, f'{parent_dir}.wav')
                
                # 重命名文件
                os.rename(os.path.join(root, file), new_filename)
                print(f'Renamed: {file} to {parent_dir}.wav')

# 用法示例
base_directory = 'C:/Users/Administrator/Desktop/111/108010slogo/spleeter'
rename_mp3_files(base_directory)

 

import os

def rename_mp3_files(root_dir):
    # 遍历指定的根目录
    for dirpath, dirnames, filenames in os.walk(root_dir):
        for filename in filenames:
            # 检查文件扩展名是否为.mp3
            if filename.lower().endswith('.wma'):
                # 获取当前文件的完整路径
                file_path = os.path.join(dirpath, filename)
                # 构造新文件名,使用子目录的名称
                new_file_name = os.path.basename(dirpath) + '.wma'
                # 获取新文件的完整路径
                new_file_path = os.path.join(dirpath, new_file_name)
                # 重命名文件
                os.rename(file_path, new_file_path)
                print(f'Renamed "{file_path}" to "{new_file_path}"')

# 调用函数,传入你想要遍历的根目录
root_directory = '.'  # 替换为你的根目录路径
rename_mp3_files(root_directory)