批量重命名Excel文件并排序

import os import logging # 配置日志记录 logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') def rename_files_with_sequence(directory): # 检查文件夹是否存在 if not os.path.isdir(directory): logging.error("Directory '{}' does not exist or is not a directory.".format(directory)) return try: # 获取指定目录中的所有 XLS 和 XLSX 文件 files = [f for f in os.listdir(directory) if f.endswith('.xls') or f.endswith('.xlsx')] # 按照文件名排序 files.sort() # 遍历文件并添加序号前缀 for index, filename in enumerate(files, start=1): # 分离文件名和扩展名 file_base, file_ext = os.path.splitext(filename) # 构建新的文件名 new_filename = "{}、{}{}".format(index, file_base, file_ext) # 获取旧文件和新文件的完整路径 old_file_path = os.path.join(directory, filename) new_file_path = os.path.join(directory, new_filename) # 检查新文件是否已存在 if os.path.exists(new_file_path): logging.warning("{} already exists. Skipping.".format(new_filename)) continue # 重命名文件 os.rename(old_file_path, new_file_path) logging.info("Renamed: {} -> {}".format(filename, new_filename)) except Exception as e: logging.error("An error occurred: {}".format(e)) # 指定你的文件夹路径 directory_path = r"D:\桌面\2024年外宣上稿情况" # 执行重命名操作 rename_files_with_sequence(directory_path)
上一篇:Android 老项目适配 Compose 混合开发


下一篇:3588 yolov8 onnx 量化转 rknn 并运行