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

如何将CSV中正序姓名匹配到倒序命名文件并迁移至指定文件夹?

解决方案:基于CSV姓名列表匹配并移动文件

核心思路

  1. 解析CSV中的Firstname MI. Lastname格式姓名,提取名和姓,转换为小写的lastnamefirstname格式作为匹配前缀
  2. 遍历目标文件夹,筛选文件名前缀与匹配前缀一致的文件
  3. 将匹配文件移动到指定的单独文件夹

实现代码(Python标准库,无需额外依赖)

import csv
import os
import shutil

# 配置参数,根据实际路径修改
CSV_FILE = "你的姓名列表.csv"
SOURCE_DIR = "待匹配的文件文件夹"
TARGET_DIR = "匹配结果保存文件夹"

# 创建目标文件夹(不存在则自动创建)
os.makedirs(TARGET_DIR, exist_ok=True)

# 生成需要匹配的前缀列表
match_prefixes = []
with open(CSV_FILE, newline='', encoding='utf-8') as f:
    reader = csv.DictReader(f)
    for row in reader:
        # 清理姓名:去除首尾空格、末尾可能的点(比如"Johnson." → "Johnson")
        full_name = row['Name'].strip().rstrip('.')
        # 拆分姓名,取第一个部分(名)和最后一个部分(姓)
        name_parts = full_name.split()
        first_name = name_parts[0].lower()
        last_name = name_parts[-1].lower()
        # 拼接成匹配前缀:lastnamefirstname
        match_prefixes.append(f"{last_name}{first_name}")

# 遍历源文件夹,匹配并移动文件
for filename in os.listdir(SOURCE_DIR):
    file_path = os.path.join(SOURCE_DIR, filename)
    # 只处理文件(跳过子文件夹)
    if os.path.isfile(file_path):
        # 提取文件名下划线前的部分作为匹配项
        file_prefix = filename.split('_')[0].lower()
        if file_prefix in match_prefixes:
            shutil.move(file_path, os.path.join(TARGET_DIR, filename))
            print(f"已移动: {filename}")

优化与扩展

  1. 鲁棒的姓名解析:如果存在双姓、中间名无点等特殊格式,可改用正则表达式提取名和姓:

    import re
    # 替换姓名处理部分
    pattern = r'^(\w+)\s.*?\s(\w+)\.?$'
    match = re.match(pattern, full_name)
    if match:
        first_name = match.group(1).lower()
        last_name = match.group(2).lower()
    
  2. 递归遍历子文件夹:如果源文件夹包含子文件夹,改用os.walk遍历:

    for root, _, files in os.walk(SOURCE_DIR):
        for filename in files:
            file_path = os.path.join(root, filename)
            file_prefix = filename.split('_')[0].lower()
            if file_prefix in match_prefixes:
                shutil.move(file_path, os.path.join(TARGET_DIR, filename))
    
  3. 使用Pandas简化CSV处理:如果已安装Pandas,代码可更简洁:

    import pandas as pd
    import os
    import shutil
    
    df = pd.read_csv(CSV_FILE)
    # 清理姓名并生成匹配前缀
    df['clean_name'] = df['Name'].str.strip().str.rstrip('.')
    df['match_prefix'] = df['clean_name'].str.split().str[-1].str.lower() + df['clean_name'].str.split().str[0].str.lower()
    match_prefixes = df['match_prefix'].tolist()
    
    # 移动文件逻辑同前
    os.makedirs(TARGET_DIR, exist_ok=True)
    for filename in os.listdir(SOURCE_DIR):
        file_path = os.path.join(SOURCE_DIR, filename)
        if os.path.isfile(file_path):
            file_prefix = filename.split('_')[0].lower()
            if file_prefix in match_prefixes:
                shutil.move(file_path, os.path.join(TARGET_DIR, filename))
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 16:03:15