You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写Python脚本每日根据数据库信息重命名对应文件夹

Python脚本实现文件夹批量重命名(基于数据库姓名映射)

实现思路

  1. 从数据库的xyz表中读取Name和Surname的对应关系,生成姓名-姓氏映射字典
  2. 遍历目标目录下的所有文件夹,匹配映射字典中的姓名,将文件夹重命名为对应的姓氏
  3. 加入异常处理,避免因文件不存在、权限问题等导致脚本中断

准备工作

先安装数据库连接依赖(根据你的数据库类型选择):

  • SQL Server:pip install pyodbc
  • MySQL:pip install pymysql
  • PostgreSQL:pip install psycopg2-binary

脚本示例(以SQL Server为例)

import os
import pyodbc

def get_name_surname_mapping():
    # 数据库连接配置,根据实际情况修改
    server = '你的数据库服务器地址'
    database = '你的数据库名'
    username = '用户名'
    password = '密码'
    conn_str = f'DRIVER={{ODBC Driver 17 for SQL Server}};SERVER={server};DATABASE={database};UID={username};PWD={password}'
    
    name_map = {}
    try:
        with pyodbc.connect(conn_str) as conn:
            cursor = conn.cursor()
            # 查询xyz表中的Name和Surname数据
            cursor.execute("SELECT Name, Surname FROM xyz")
            rows = cursor.fetchall()
            for row in rows:
                name = row[0].strip()
                surname = row[1].strip()
                name_map[name] = surname
    except Exception as e:
        print(f"数据库连接或查询出错: {str(e)}")
    return name_map

def rename_folders(root_dir, name_map):
    # 遍历根目录下的所有文件夹
    for folder_name in os.listdir(root_dir):
        folder_path = os.path.join(root_dir, folder_name)
        # 只处理文件夹,跳过文件
        if not os.path.isdir(folder_path):
            continue
        
        # 如果文件夹名在映射字典中
        if folder_name in name_map:
            new_folder_name = name_map[folder_name]
            new_folder_path = os.path.join(root_dir, new_folder_name)
            
            # 检查目标文件夹是否已存在,避免覆盖
            if not os.path.exists(new_folder_path):
                try:
                    os.rename(folder_path, new_folder_path)
                    print(f"已重命名: {folder_name} -> {new_folder_name}")
                except Exception as e:
                    print(f"重命名{folder_name}失败: {str(e)}")
            else:
                print(f"目标文件夹{new_folder_name}已存在,跳过{folder_name}")

if __name__ == "__main__":
    # 替换为存放姓名文件夹的根目录路径
    target_root_dir = r"C:\表单上传文件存储目录"
    # 获取姓名-姓氏映射
    surname_map = get_name_surname_mapping()
    # 执行重命名
    rename_folders(target_root_dir, surname_map)

适配其他数据库的修改说明

如果是MySQL,修改get_name_surname_mapping函数:

import pymysql

def get_name_surname_mapping():
    server = '你的数据库服务器地址'
    database = '你的数据库名'
    username = '用户名'
    password = '密码'
    name_map = {}
    try:
        with pymysql.connect(host=server, user=username, password=password, database=database) as conn:
            with conn.cursor() as cursor:
                cursor.execute("SELECT Name, Surname FROM xyz")
                rows = cursor.fetchall()
                for name, surname in rows:
                    name_map[name.strip()] = surname.strip()
    except Exception as e:
        print(f"数据库连接或查询出错: {str(e)}")
    return name_map

每日自动运行设置

  • Windows:打开「任务计划程序」,创建基本任务,设置每日触发时间,选择运行该Python脚本
  • Linux/macOS:编辑crontab(crontab -e),添加类似0 9 * * * /usr/bin/python3 /path/to/your/script.py(每天9点运行)

内容的提问来源于stack exchange,提问作者GD201

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 06:40:20