批量添加和修改文件拓展名
当你拿到了大批量的文件,但是文件拓展名却因为各种原因出了 bug,那么此时用代码批量处理肯定比手敲要效率高的多
批量添加文件拓展名
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| import os
def add_extension_to_files(directory, extension): """ 遍历指定目录,为每个文件添加扩展名。
:param directory: 要遍历的目录路径 :param extension: 要添加的扩展名(包括点,例如 '.txt') """ if not os.path.exists(directory): print("指定的目录不存在") return
for filename in os.listdir(directory): file_path = os.path.join(directory, filename) if os.path.isfile(file_path): name, _ = os.path.splitext(file_path) new_file_path = f"{name}{extension}" os.rename(file_path, new_file_path) print(f"文件 {filename} 已重命名为 {new_file_path}")
directory_path = 'D:/example' extension_to_add = '.zip' add_extension_to_files(directory_path, extension_to_add)
|
批量修改文件拓展名
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| import os
def rename_extension(directory, old_extension, new_extension): """ 遍历指定目录,将所有指定扩展名的文件批量修改为新的扩展名。
:param directory: 要遍历的目录路径 :param old_extension: 原始扩展名(包括点,例如 '.txt') :param new_extension: 新扩展名(包括点,例如 '.md') """ if not os.path.exists(directory): print("指定的目录不存在") return
for filename in os.listdir(directory): file_path = os.path.join(directory, filename) if os.path.isfile(file_path) and filename.endswith(old_extension): name, _ = os.path.splitext(file_path) new_file_path = f"{name}{new_extension}" os.rename(file_path, new_file_path) print(f"文件 {filename} 已重命名为 {new_file_path}")
directory_path = 'D:/example' old_extension = '.zip' new_extension = '.md' rename_extension(directory_path, old_extension, new_extension)
|