本节目录
常用函数一:批量文件重命名
常用函数一:批量文件重命名
# -*- coding: utf-8 -*- """ DateTime : 2021/02/08 10:29 Author : ZhangYafei Description: 批量文件重命名 """ import os def rename(path, prefix: str = None, suffix: str = None, replace: dict = None, append: bool = False, remove: bool = False, file_type: bool = False): origin_path = path dir_path, path = os.path.split(path) path, file_type_suffix = path.rsplit('.', maxsplit=1) if file_type else (path, None) if append: if prefix: path = f'{prefix}{path}' if suffix: path = f'{path}{suffix}' if replace: for key, val in replace: path = path.replace(key, val) elif remove: if prefix and path.startswith(prefix): path = path[len(prefix):] if suffix: path = path[:-len(suffix)] if replace: for key, val in replace: path = path.replace(key, val) elif replace: for key in replace: path = path.replace(key, replace[key]) if file_type: path = f'{path}.{file_type_suffix}' if dir_path: path = os.path.join(dir_path, path) os.rename(origin_path, path) print(f'{origin_path} rename to {path} success.') def batch_file_rename(dir_path: str, only_file: bool = False, only_dir: bool = False, prefix: str = None, suffix: str = None, replace: dict = None, append: bool = False, remove: bool = False, file_type: bool =False): """ 批量文件重命名 :param dir_path: 文件夹名称 :param only_file: 是否仅修改文件 :param only_dir: 是否仅修改文件夹 :param prefix: 前缀 :param suffix: 后缀 :param replace: 替换 :param append: 插入 :param remove: 删除 :param file_type: 文件类型 :return: """ if not any([append, remove, replace]): raise Exception('append OR remove OR replace at least one is not None.') if only_file: for base_path, folders, files in os.walk(dir_path): for file in files: file_path = os.path.join(base_path, file) rename(file_path, prefix=prefix, suffix=suffix, replace=replace, append=append, remove=remove, file_type=file_type) elif only_dir: for base_path, folders, files in os.walk(dir_path): for folder in folders: folder_path = os.path.join(base_path, folder) rename(folder_path, prefix=prefix, suffix=suffix, replace=replace, append=append, remove=remove, file_type=file_type) else: for base_path, folders, files in os.walk(dir_path): for folder in folders: folder_path = os.path.join(base_path, folder) rename(folder_path, prefix=prefix, suffix=suffix, replace=replace, append=append, remove=remove, file_type=file_type) for file in files: file_path = os.path.join(base_path, file) rename(file_path, prefix=prefix, suffix=suffix, replace=replace, append=append, remove=remove, file_type=file_type) if __name__ == '__main__': # batch_file_rename('data', suffix='[张亚飞出品]', append=True, file_type=True) # batch_file_rename('data', replace={'[张亚飞出品]': ''}) # batch_file_rename('data', prefix='[张亚飞]', append=True) batch_file_rename('data', prefix='[张亚飞]', remove=True)
运行结果