批量重命名Excel文件并排序
python环境:3.5.2
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))returntry:# 获取指定目录中的所有 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)